我們經常說union和union all的區別在於:
1.union 合併相同的列時,會去重只取其中的一條;
2.union all 合併所有的列。
但是如果在按照某一條件進行查詢時,如果表中數據沒有符合該條件的記錄。(即按此條件查詢,表中查找到的的記錄每列都爲空)此時union all並不能合併這種空的記錄。
比如新建一個表名爲t_student的表。記錄學生的姓名,性別,年齡和成績等基礎信息。
在t_student表中查詢名爲李明,小河,張三的姓名和成績。
select username,grade from t_student where username ='李明'
union all
select username,grade from t_student where username ='小河'
union all
select username,grade from t_student where username ='張三'
查詢結果如下:
我們可以發現如果在t_student表中並沒有張三的信息,那麼使用union all,爲空的記錄並不會在出現查詢結果中。但是如果在t_student表添加名爲張三的一列(除學生姓名外,他們列都爲空)都會在查詢結果中顯示張三的記錄。