简体   繁体   中英

Join tables and sort by 2 different columns

I have query that make a list of payments (payment table) and I would like to have it sorted by the date of the tasks (2 separate tables - quotedb and packaging) these payments are related to

My Query:

SELECT a.* 
FROM payments AS a 
LEFT JOIN quotedb AS b ON a.orderid = b.id  
LEFT JOIN packaging AS p ON a.orderid = p.id  
WHERE a.status='Pending' AND (b.moveday<'$today' OR p.datestamp<'$today')
ORDER BY b.moveday, p.datestamp

payments table example:

id payment   orderid
------------------- 
1  payment1  1
2  payment2  2
3  payment3  3
4  payment4  4
5  payment5  5
6  payment6  6

quotedb table example:

id moveday
-----------
1  05.07.18  > related to payments table id 1
2  08.07.18  
3  10.07.18

packaging table example:

id datestamp
-----------
4  06.07.18  > related to payments table id 4
5  07.07.18
6  19.07.18

I join results from the tables, but I have a problem with sorting, query seem to print the "packaging" table results unsorted, and then results from "quotedb" sorted by moveday

I want these results to be sorted by (joined moveday and datestamp)

You can use UNION ALL to combine quotedb and packaging tables. and use grp make a number to make Order by sequence number

SELECT a.* 
FROM payments a 
LEFT JOIN
(
    SELECT 1 grp,id,moveday AS day
    FROM quotedb
    UNION ALL
    SELECT 2,id,datestamp
    FROM packaging
) t on a.orderid = t.id
ORDER BY t.grp,t.day

sqlfiddle

SELECT a.* 
FROM payments AS a 
LEFT JOIN
(
    SELECT orderno, moveday AS sortdate FROM quotedb 
    UNION ALL
    SELECT orderno, datestamp AS sortdate FROM packaging
) t on a.orderno = t.orderno
WHERE a.status='Pending' AND sortdate<'$today'
ORDER BY sortdate

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