我有一个查询,该查询列出了付款的列表(付款表),我想按任务的日期(与付款相关的2个单独的表-quotedb和包装)进行排序
我的查询
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
所以我联接了表的结果,但是我在排序时遇到了问题,查询似乎将未排序的“包装”表结果打印出来,然后将“ quotedb”的结果按Moveday排序
我希望对这些结果进行排序(加入移动日和日期戳)
需要帮助,Thx伙计们。
答案 0 :(得分:2)
您可以使用UNION ALL
合并quotedb
和packaging
表。并使用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
答案 1 :(得分:1)
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