MySql数据库查询(DQL)语言—union联合查询

union联合查询

一、概念
union联合,合并,联合查询就是将多条查询语句的结果合并成一个结果。

二、语法
查询语句1
union
查询语句2
union
查询语句3

三、特点

  • 要求多条查询语句的查询列数是一致的
  • 要求多条查询语句的查询列的类型和顺序最好一致
  • union默认是去重的,使用union all可以包含重复数据

四、应用场景
要查询的结果来自于多张表,并且表之间没有直接的连接关系,但查询的信息一致。

五、案例

  1. 查询部门编号>90或邮箱包含a的员工信息。
    常规写法:
    select * from employees where department_id > 90 or email like "%a%";
    联合查询写法:
    select * from employees wherer department_id > 90 union select * from employees where email like "%a%";

  2. 查询中国用户中男性的信息和外国用户中男性的信息(去重)。
    select * from t_ca where csex="男" union select * from t_ua where tGender = "male";

  3. 查询中国用户中男性的信息和外国用户中男性的信息(不去重)。
    select * from t_ca where csex="男" union all select * from t_ua where tGender = "male";

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