简体   繁体   中英

How to merge two tables according to time Mysql

I have following two tables "payment" and "Cancelpayment" Here is my payment table

id          bookingId       userId      status      createdON   
1           120             120         1           2020-06-01 10:24:29
2           124             120         1           2020-06-03 18:25:22 
3           126             120         1           2020-06-06 22:21:33
4           128             121         1           2020-06-06 22:28:11

Here is my table "cancelpayment"

id          bookingId       userId      status      createdON
1           121             120         1           2020-06-02 10:11:14 
2           123             120         1           2020-06-03 13:14:28

I want to merge both table means i want get all record of user (userid=120) from both tables but according to createdON means whether user record in "payment" table or "cancelpayment" should be showing Assending

I tried with following code but not working for me

SELECT bookingId as BookingId,status,createdON FROM cancelpayment WHERE userId='120' 
UNION 
SELECT bookingId as BookingId,status,createdON FROM payment WHERE userId='120'

Add a computed column:

SELECT BookingId, status, createdON
FROM
(
    SELECT userId, bookingId AS BookingId, status, createdON, 1 AS src
    FROM payment
    WHERE userId = '120' 
    UNION ALL
    SELECT userId, bookingId, status, createdON, 2
    FROM cancelpayment
    WHERE userId = '120'
) t
ORDER BY
    userId,
    src;

You have to pass **ORDER BY createdON ASC** in your query like this:

SELECT bookingId as BookingId,status,createdON FROM cancelpayment WHERE userId='120'
UNION 
SELECT bookingId as BookingId,status,createdON FROM payment WHERE userId='120' 
ORDER BY createdON ASC

MySQL Output:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM