How to execute UNION without sorting? (SQL)

前端 未结 10 611
猫巷女王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:00

    I notice this question gets quite a lot of views so I'll first address a question you didn't ask!

    Regarding the title. To achieve a "Sql Union All with “distinct”" then simply replace UNION ALL with UNION. This has the effect of removing duplicates.

    For your specific question, given the clarification "The first query should have "priority", so duplicates should be removed from bottom" you can use

    SELECT col1,
           col2,
           MIN(grp) AS source_group
    FROM   (SELECT 1 AS grp,
                   col1,
                   col2
            FROM   t1
            UNION ALL
            SELECT 2 AS grp,
                   col1,
                   col2
            FROM   t2) AS t
    GROUP  BY col1,
              col2
    ORDER  BY MIN(grp),
              col1  
    

提交回复
热议问题