我想在带有联合运算符的内部选择查询中使用 order by 子句,即
select colname from table where <cond1> order by colname
union
select colname from table where <cond2> order by colname
我可以将 order by 与完整结果一起使用,但我希望将第一个查询的结果排序,然后将第二个查询的结果排序。
请给我一些建议。
Order by
in unioned
table的正确用法是
select colname from table where <cond1>
union
select colname from table where <cond2> order by colname
上面代码的解释是,在两个查询合并后,它会根据列名进行排序。在服务器将它与第一个查询联合之前,它不会先对较低的查询进行排序。但是有一种替代方法,您需要将其包装在子查询中。
SELECT newTable.colname
FROM
(
select colname, 1 as OrderThis from table where <cond1>
union
select colname, 2 as OrderThis from table where <cond2>
) newTable
Order by newTable.OrderThis, newTable.colname
如果我的想法正确,您希望union
在两个查询正确并保持其正确位置之前先对列进行排序(第一个查询结果保持在顶部,而第二个查询结果保持在第一个查询下方)
以下应该做......我猜
select colname,1 as OrderCol from table where <cond1>
union select colname,2 as OrderCol from table
where <cond2>
order by OrderCol
这可能会奏效
SELECT * FROM ( SELECT colname FROM table1 where <cond1> order by colname ) DUMMY_ALIAS1
UNION ALL
SELECT * FROM ( SELECT colname FROM table2 where <cond2> order by colname ) DUMMY_ALIAS2