How to execute UNION without sorting? (SQL)

前端 未结 10 593
猫巷女王i
猫巷女王i 2021-01-30 21:34

UNION joins two results and remove duplicates, while UNION ALL does not remove duplicates.
UNION also sort the final output.

W

10条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-30 22:13

    The sort is used to eliminate the duplicates, and is implicit for DISTINCT and UNION queries (but not UNION ALL) - you could still specify the columns you'd prefer to order by if you need them sorted by specific columns.

    For example, if you wanted to sort by the result sets, you could introduce an additional column, and sort by that first:

    SELECT foo, bar, 1 as ResultSet
    FROM Foo
    WHERE bar = 1
    UNION
    SELECT foo, bar, 2 as ResultSet
    FROM Foo
    WHERE bar = 3
    UNION
    SELECT foo, bar, 3 as ResultSet
    FROM Foo
    WHERE bar = 2
    ORDER BY ResultSet
    

提交回复
热议问题