连接表并按2个不同的列排序

osh3o9ms  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(386)

我有一个查询,使付款列表(付款表),我想有它的任务(2个单独的表-报价和 Package )这些付款相关的日期排序
我的问题:

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

付款表示例:

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

quotedb表格示例:

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

Package 表示例:

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

我连接了来自表的结果,但是我在排序方面有一个问题,查询似乎打印了未排序的“打包”表结果,然后是按moveday排序的“quotedb”结果
我希望这些结果按(日期和日期戳)排序

gr8qqesn

gr8qqesn1#

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
rryofs0p

rryofs0p2#

你可以用 UNION ALL 合并 quotedb 以及 packaging table。使用 grp 编一个数字 Order by 序列号

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公司

相关问题