0
点赞
收藏
分享

微信扫一扫

SQL语句:联合查询

一条咸鱼的干货 2021-09-24 阅读 70
数据库

联合查询UNION

  • 作用:将多条select语句的结果,合并到一起,称之为联合操作。
  • 语法:( ) UNION ( )
  • 要求查询时,多个select语句的检索到的字段数量必须一致
  • 每一条记录的各字段类型和顺序最好是一致的
  • UNION关键字默认去重,可以使用UNION ALL包含重复项
mysql> (select 'yes') union (select 'yes');
+-----+
| yes |
+-----+
| yes |
+-----+
1 row in set (0.00 sec)


mysql> (select 'yes') union all (select 'yes');
+-----+
| yes |
+-----+
| yes |
| yes |
+-----+
2 rows in set (0.00 sec)
  • 例,某生产商有一张原材料表和一张商品表,需要把原材料价格和商品价格一起输出

  • 查询1972年或2000年后出生的员工

# 普通方法
mysql> select name, birth_date from employees
    -> where year(birth_date)<1972 or year(birth_date)>2000;
+-----------+------------+
| name      | birth_date |
+-----------+------------+
| 梁伟      | 1971-08-19 |
| 张建平    | 1971-11-02 |
| 窦红梅    | 1971-09-09 |
| 温兰英    | 1971-08-14 |
| 朱文      | 1971-08-15 |
| 和林      | 1971-12-10 |
+-----------+------------+
6 rows in set (0.01 sec)


# 联合查询的方法
mysql> (
    -> select name, birth_date from employees
    ->   where year(birth_date)<1972
    -> )
    -> union
    -> (
    ->   select name, birth_date from employees
    ->   where year(birth_date)>2000
    -> );
+-----------+------------+
| name      | birth_date |
+-----------+------------+
| 梁伟      | 1971-08-19 |
| 张建平    | 1971-11-02 |
| 窦红梅    | 1971-09-09 |
| 温兰英    | 1971-08-14 |
| 朱文      | 1971-08-15 |
| 和林      | 1971-12-10 |
+-----------+------------+
6 rows in set (0.00 sec)
举报

相关推荐

0 条评论