union和distinct关键字

阅读量: 273 编辑

union和distinct关键字

union:将两张表或多张表的数据合并到一个列表中

distinct:筛选掉重复的数据

语法

SELECT field1, field2
FROM table1
[WHERE conditions]

UNION [ALL | DISTINCT]

SELECT field1, field2
FROM table2
[WHERE conditions]

1. 两个SELECT的 field 数量必须一致,类型名称可以不同,栏位名称以第一个SELECT的名称为标准
2. UNION 默认是 DISTINCT 的,也就是不重复的, ALL是所有的(包括重复的)

3. DISTINCT 表示非重复的数据,也就是唯一的数据
    SELECT distinct field, field2 FROM table2;
    SELECT count(distinct field) FROM table2;

代码实战

代码的详细解读,可以参考视频教程

SELECT `name`, `code` FROM classify
UNION ALL
SELECT `realname`, `password` FROM student

SELECT DISTINCT `classify` FROM course;

SELECT count(DISTINCT classify) FROM course;