简体   繁体   中英

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

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.

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. For performance reasons, SQL queries are not necessarily executed in the same sequence they are written; 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. But tomorrow, if the optimizer decides that HASH GROUP BY is fater, the results may be different.

If you want deterministic results you must fully specify the ORDER BY at the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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