How to execute UNION without sorting? (SQL)

前端 未结 10 749
猫巷女王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 21:48

    SELECT *, 1 AS sort_order
      FROM table1
     EXCEPT 
    SELECT *, 1 AS sort_order
      FROM table2
    UNION
    SELECT *, 1 AS sort_order
      FROM table1
     INTERSECT 
    SELECT *, 1 AS sort_order
      FROM table2
    UNION
    SELECT *, 2 AS sort_order
      FROM table2
     EXCEPT 
    SELECT *, 2 AS sort_order
      FROM table1
    ORDER BY sort_order;
    

    But the real answer is: other than the ORDER BY clause, the sort order will by arbitrary and not guaranteed.

提交回复
热议问题