简体   繁体   English

如何在 sql 中使用联合排序每个选择语句

[英]How order by with union in sql each select statement

each select statement order works well,每个选择语句顺序都运行良好,

but when I union both, it doesn't order result well但是当我将两者结合起来时,结果并不能很好地排序

how can I order in this query?我如何在此查询中订购?

SELECT * FROM (SELECT NM, DEP_CD, 2 AS POSITION FROM EMP WHERE DEP_CD='1100' 
and (SELECT COUNT(1) FROM BBS_TABLE WHERE UP_DEP_CD = '1100') > 0 ORDER BY NM 
DESC)
UNION
SELECT * FROM (SELECT NM, DEP_CD, 1 AS POSITION FROM EMP WHERE DEP_CD '1110' 
ORDER BY NM DESC)
ORDER BY 3 DESC

Wrap everything in one more table:把所有东西都放在一张表中:

select * from (
SELECT * FROM (SELECT NM, DEP_CD, 2 AS POSITION FROM EMP WHERE DEP_CD='1100' and (SELECT COUNT(1) FROM BBS_TABLE WHERE UP_DEP_CD = '1100') > 0 ORDER BY NM DESC)
UNION
SELECT * FROM (SELECT NM, DEP_CD, 1 AS POSITION FROM EMP WHERE DEP_CD '1110' ORDER BY NM DESC)

) ORDER BY 3 DESC

SELECT from the result created (inner_table) and sort accordingly从创建的结果(inner_table)中选择并相应地排序

SELECT * FROM (
SELECT * FROM (SELECT NM, DEP_CD, 2 AS POSITION FROM EMP WHERE DEP_CD='1100' and (SELECT COUNT(1) FROM BBS_TABLE WHERE UP_DEP_CD = '1100') > 0 ORDER BY NM DESC)
UNION
SELECT * FROM (SELECT NM, DEP_CD, 1 AS POSITION FROM EMP WHERE DEP_CD '1110' ORDER BY NM DESC)
) AS inner_table
ORDER BY 3 DESC

The only guaranteed order is the last one you ask for.唯一保证的顺序是您要求的最后一个。 If you want to order by 3 DESC and then NM DESC , you have to specify ORDER BY 3 DESC, NM DESC at the end of your query.如果您想按3 DESC然后按NM DESC排序,则必须在查询结束时指定ORDER BY 3 DESC, NM DESC

You can't order by NM DESC in the inline view and then order by 3 DESC in the outer query and expect the NM DESC ordering to be preserved.您不能NM DESC联视图中按NM DESC排序,然后在外部查询中按3 DESC NM DESC排序并期望保留NM DESC排序。 For performance reasons, SQL queries are not necessarily executed in the same sequence they are written;出于性能原因,SQL 查询不一定按照它们编写的顺序执行; when rows flow from one step of the query to another the ordering may not be preserved.当行从查询的一个步骤流到另一个步骤时,可能不会保留排序。

Beware of tricks that may appear to return the correct order without specifying it.当心那些看似没有指定就返回正确顺序的技巧。 There are some operations that return rows in a preserved order, but you do not want your results to depend on the internal operations chosen by the optimizer.有一些操作以保留的顺序返回行,但您不希望结果依赖于优化器选择的内部操作。 For example, if your UNION uses a SORT GROUP BY the results may look fine.例如,如果您的UNION使用SORT GROUP BY ,结果可能看起来不错。 But tomorrow, if the optimizer decides that HASH GROUP BY is fater, the results may be different.但是明天,如果优化器决定HASH GROUP BY更早,结果可能会有所不同。

If you want deterministic results you must fully specify the ORDER BY at the end.如果你想要确定性的结果,你必须在最后完全指定ORDER BY

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM