📅  最后修改于: 2023-12-03 14:47:36.860000             🧑  作者: Mango
SQL中的联合条款(UNION)可以将多个SELECT语句的结果合并为一张表,常用于对不同表或同一表的不同条件进行查询,将结果合并展示。
SELECT column1, column2, ... FROM table1 WHERE condition1
UNION
SELECT column1, column2, ... FROM table2 WHERE condition2
UNION
...
ORDER BY column1, column2, ...
注意:
可以将多个表按照指定条件进行联合查询,展示结果。
示例:
SELECT employee_id, first_name, last_name FROM employees WHERE department_id = 50
UNION
SELECT employee_id, first_name, last_name FROM employees WHERE department_id = 80
ORDER BY last_name ASC;
以上SQL语句将展示部门ID为50和80的所有员工的ID、姓名,按照姓氏升序排列。
也可以对同一张表的不同条件进行查询,将结果集联合展示。
示例:
SELECT department_id, COUNT(*) as emp_count, 'Full-time' as emp_type FROM employees WHERE job_id = 'IT_PROG' GROUP BY department_id
UNION
SELECT department_id, COUNT(*) as emp_count, 'Part-time' as emp_type FROM employees WHERE job_id = 'ST_CLERK' GROUP BY department_id
ORDER BY department_id ASC, emp_type DESC;
以上SQL语句将展示所有IT_PROG和ST_CLERK职位员工的部门ID、数量和雇佣类型,按照部门ID升序排列,雇佣类型降序排列。
SQL联合条款可以对多个表或同一表的不同条件进行查询,将结果集联合展示。注意字段数量和数据类型必须一致,可以添加ORDER BY语句按照指定字段排序。