MySQL查询返回没有顺序的结果

时间:2015-11-16 20:39:07

标签: php mysql select union

我正在尝试在' orderindex'中组织查询输出。为了在我的php函数循环中使用mysql正确显示列表。

目前我的SQL查询是这样的:

SELECT * FROM (SELECT NewCustInfo.Driver, SUBSTRING_INDEX(NewCustInfo.Driver, '/', -1) AS orderindex, SUBSTRING_INDEX(NewCustInfo.Driver, '/', 1) AS thedriver, NewCustInfo.id,NewCustInfo.Accomplished
 FROM NewCustInfo WHERE NewCustInfo.Driver REGEXP 'Test123/' AND NewCustInfo.Accomplished='0' ORDER BY orderindex DESC) DUMMY_ALIAS1
UNION ALL
SELECT * FROM (SELECT PickupSlip.Driver, SUBSTRING_INDEX(PickupSlip.Driver, '/', -1) AS orderindex, SUBSTRING_INDEX(PickupSlip.Driver, '/', 1) AS thedriver, PickupSlip.id,PickupSlip.Accomplished
 FROM PickupSlip WHERE PickupSlip.Driver REGEXP 'Test123/' AND PickupSlip.Accomplished='0' ORDER BY orderindex DESC) DUMMY_ALIAS2
UNION ALL
SELECT * FROM (SELECT DeliverySlip.Driver, SUBSTRING_INDEX(DeliverySlip.Driver, '/', -1) AS orderindex, SUBSTRING_INDEX(DeliverySlip.Driver, '/', 1) AS thedriver, DeliverySlip.id,DeliverySlip.Accomplished
 FROM DeliverySlip WHERE DeliverySlip.Driver REGEXP 'Test123/' AND DeliverySlip.Accomplished='0' ORDER BY orderindex DESC) DUMMY_ALIAS3

我意识到这是按SELECT排序,而不是整个查询。有没有办法订购所有3个SELECTS的完整结果?

e.g。将3个选项转换为变量,然后以某种方式将它们连接成一个列表,然后用ORDER BY显示?

1 个答案:

答案 0 :(得分:1)

根据UNION上mysql的语法,在最后一次选择后放置一个order by子句:

(SELECT a FROM t1 WHERE a=10 AND B=1)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2)
ORDER BY a