我已经发现了我所说的复杂的sql查询,我需要实现更好的排序。我会给你一个更简单的版本,希望解决方案适用于原版。
假设我有两个表格,我正在应用UNION
。我想订购每个表的结果,然后是结果表本身。
我们说我有这些表格:
文件夹:
Name CreateDate
------------------
Music 2015-11-12
Videos 2012-11-12
文件:
Name CreateDate
------------------
file1 2014-11-12
file2 2013-11-12
用户可以通过Name或CreateDate对它们进行排序,但在结果中,文件夹始终必须首先出现。
我会写这样的东西:
Select *
From (
Select Name, CreateDate, 1 as tableOrder
From Folders
Order by
CASE WHEN @NameOrder = 1 THEN Name END ASC,
CASE WHEN @DateOrder = 1 THEN CreateDate END ASC
UNION
Select Name, CreateDate, 2 as tableOrder
From Files
Order by
CASE WHEN @NameOrder = 1 THEN Name END ASC,
CASE WHEN @DateOrder = 1 THEN CreateDate END ASC
)
Order by tableOrder
但我知道我只能在工会之后才能使用订单。我怎么能做到这一点?
答案 0 :(得分:2)
在派生表中执行UNION
。订购它的结果,将tableOrder放在ORDER BY
:
select * from
(
Select Name, CreateDate, 1 as tableOrder
From Folders
UNION
Select Name, CreateDate, 2 as tableOrder
From Files
) dt
Order by tableOrder,
CASE WHEN @NameOrder = 1 THEN Name END ASC,
CASE WHEN @DateOrder = 1 THEN CreateDate END ASC
答案 1 :(得分:2)
您的查询有多个问题。首先,在最外面的查询中,ORDER BY
仅确定 的查询顺序。其次,您正在使用UNION
,这会产生额外的开销以删除重复项。
解决这些问题:
Select Name, CreateDate, which
From ((Select Name, CreateDate, 1 as tableOrder
From Folders
) UNION ALL
(Select Name, CreateDate, 2 as tableOrder
From Files
)
) ff
Order by tableOrder,
(CASE WHEN @NameOrder = 1 THEN Name END) ASC,
(CASE WHEN @DateOrder = 1 THEN CreateDate END) ASC ;