union:對多個結果集進行並集操作,不包括重複行,同時進行排序。
union all:對多個結果集進行並集操作,包括重複行,不進行排序。
查詢部門小於30號的員工訊息,和部門大於20小於40號的員工資訊。
①.先查詢部門小於30號的員工資料。
SELECT employees_id ,last_name ,salary ,department_id FROM employees WHERE department_id < 30; ```
查詢部門大於20小於40的員工資料。
SELECT employees_id ,last_name ,salary ,department_id FROM employees WHERE department_id BETWEEN 20 and 40;```
③.用union連接兩張表
SELECT employees_id ,last_name ,salary ,department_id FROM employees WHERE department_id < 30 UNION SELECT employees_id ,last_name ,salary ,department_id FROM employees WHERE department_id BETWEEN 20 and 40; ```
其結果預設排序並去重,兩張表都有30號部門信息,結果只出現一次。
④.下面用union all連接兩張表
SELECT employees_id ,last_name ,salary ,department_id FROM employees WHERE department_id < 30 UNION ALL SELECT employees_id ,last_name ,salary ,department_id FROM employees WHERE department_id BETWEEN 20 and 40; ```
其結果沒有去重,也沒有排序,排序結果對比下邊結果,先去查詢20到40的員工信息,在查小於30的員工資訊。
⑤.比較查詢結果
SELECT employees_id ,last_name ,salary ,department_id FROM employees WHERE department_id BETWEEN 20 and 40 UNION ALL SELECT employees_id ,last_name ,salary ,department_id FROM employees WHERE department_id < 30;```
預設是沒有進行排序的。
以上是MySQL中union和unionall差別是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!