1

我有这些疑问:

(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为零的记录,但它们没有按日期排序...特别是顺序有效...为什么?我尝试使用唯一的顺序,但结果混合了 var 等于或不为零的记录...

4

3 回答 3

5

您必须最后申请订单:

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

如果您想保留两个部分的顺序,请编辑,所以首先使用var<>'0'(内部排序date DESC),然后全部使用var='0'(内部排序date DESC):

SELECT * FROM product WHERE var<>'0'
UNION 
SELECT * FROM product WHERE var='0'
ORDER BY 
    CASE WHEN var<>'0' THEN 0 ELSE 1 END ASC,
    date DESC
于 2013-01-03T15:13:55.610 回答
2

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

SELECT *
FROM product
WHERE var IS NOT NULL
ORDER BY CASE WHEN var = '0' THEN 2 ELSE 1 END, date DESC
于 2013-01-03T15:21:34.843 回答
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
于 2013-01-03T15:15:02.477 回答