按日期说明说明问题

时间:2013-01-03 15:12:49

标签: sql date union

我有这些疑问:

(SELECT * FROM product WHERE var<>'0'ORDER BY date DESC) 

(SELECT * FROM product WHERE var='0' ORDER BY date DESC).

当我尝试将两者的结果合并为

 (SELECT * FROM product WHERE var<>'0'ORDER BY date DESC) 
 UNION 
 (SELECT * FROM product WHERE var='0' ORDER BY date DESC)

结果失去了订单...结果集首先包含var不为零的所有记录,然后所有记录的变量为零但是它们没有按日期排序...奇怪的是订单正在运行......为什么? 我尝试使用一个唯一的顺序,但结果混合了var等于或不等于零的记录...

3 个答案:

答案 0 :(得分:5)

您必须最后应用订单:

SELECT * FROM product WHERE var<>'0'
UNION 
SELECT * FROM product WHERE var='0'
ORDER BY date DESC

修改,如果您想要在两个部分中保留订单,那么首先使用var<>'0'(内部按date DESC排序),然后全部使用{{1} }(由var='0'内部排序):

date DESC

答案 1 :(得分:2)

我相信你要做的是订购结果集最后放'0',然后按日期订购每个子集。在这种情况下,您可以忘记联合并改为执行此操作:

SELECT *
FROM product
WHERE var IS NOT NULL
ORDER BY CASE WHEN var = '0' THEN 2 ELSE 1 END, date DESC

答案 2 :(得分:0)

SELECT * FROM product WHERE var<>'0'
UNION 
SELECT * FROM product WHERE var='0'
ORDER BY date DESC

相当于:

SELECT * FROM product
ORDER BY date DESC