一蓖康、概述
union
和union all
都用于合并多個查詢,用法為:
select * from a union select * from b;
select * from a union all select * from b;
兩者的區(qū)別是union all
合并的結(jié)果中會有重復(fù)記錄,而union
中沒有。
二停做、示例
創(chuàng)建兩張表chinese和math分別表示語文課和數(shù)學(xué)課的選課情況:
CREATE TABLE chinese (
id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL
);
INSERT INTO chinese (name) VALUES ('小明'), ('小花'), ('小白'), ('小剛');
CREATE TABLE math (
id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20) NOT NULL
);
INSERT INTO math (name) VALUES ('小明'), ('小李'), ('老王');
2.1 union
SELECT name FROM chinese
UNION
SELECT name FROM math;
結(jié)果中沒有重復(fù)記錄小明
:
image.png
2.2 union all
SELECT name FROM chinese
UNION ALL
SELECT name FROM math;
結(jié)果中有重復(fù)記錄小明
:
image.png