What is the difference between UNION and UNION ALL?

后端 未结 26 2337
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 11:28

What is the difference between UNION and UNION ALL?

26条回答
  •  伪装坚强ぢ
    2020-11-21 12:00

    Important! Difference between Oracle and Mysql: Let's say that t1 t2 don't have duplicate rows between them but they have duplicate rows individual. Example: t1 has sales from 2017 and t2 from 2018

    SELECT T1.YEAR, T1.PRODUCT FROM T1
    
    UNION ALL
    
    SELECT T2.YEAR, T2.PRODUCT FROM T2
    

    In ORACLE UNION ALL fetches all rows from both tables. The same will occur in MySQL.

    However:

    SELECT T1.YEAR, T1.PRODUCT FROM T1
    
    UNION
    
    SELECT T2.YEAR, T2.PRODUCT FROM T2
    

    In ORACLE, UNION fetches all rows from both tables because there are no duplicate values between t1 and t2. On the other hand in MySQL the resultset will have fewer rows because there will be duplicate rows within table t1 and also within table t2!

提交回复
热议问题