MySQL 合并查询结果(Union 关键字)

利用 UNION关键字,可以将多个select语句的结果组合成单个结果集。

mysql> select * from students;
+----+--------+-------+------+------+
| id | number | name  | sex  | age  |
+----+--------+-------+------+------+
|  1 |   1111 | LiLy  | W    |   12 |
|  2 |   1112 | Lucy  | W    |   11 |
|  3 |   1113 | LiLei | M    |   13 |
|  4 |   1117 | Bird  | NULL |   33 |
+----+--------+-------+------+------+
4 rows in set (0.00 sec)

mysql> select id,number,name,age from students where age<13 union select id,number,name,age from students where id in(1,4);
+----+--------+------+------+
| id | number | name | age  |
+----+--------+------+------+
|  1 |   1111 | LiLy |   12 |
|  2 |   1112 | Lucy |   11 |
|  4 |   1117 | Bird |   33 |
+----+--------+------+------+
3 rows in set (0.00 sec)

可以看到,UNION会把 重复的行去掉,返回的行都是唯一的。如果想保留重复行,可以使用 UNION ALL 关键字。

mysql> select id,number,name,age from students where age<13 union all select id,number,name,age from students where id in(1,4);
+----+--------+------+------+
| id | number | name | age  |
+----+--------+------+------+
|  1 |   1111 | LiLy |   12 |
|  2 |   1112 | Lucy |   11 |
|  1 |   1111 | LiLy |   12 |
|  4 |   1117 | Bird |   33 |
+----+--------+------+------+
4 rows in set (0.00 sec)

UNION ALL 关键字执行时需要的资源少,因此在查询结果中没有重复数据或者不需要去掉重复数据的时候,最好使用UNION ALL提高查询效率。

你可能感兴趣的:(数据库)