联合查询的规则是:

字段的个数和顺序必须相同

查询中的相应字段必须具有兼容的数据类型
要对合并后的结果集进行排序,可以在最后一个查询后面加上 order by 只在最后一个查询后面加,不是每个查询都加。

1.union

union会移除所有重复的行,要保留重复的行,需要使用 union all。

-- 有语文成绩或数学成绩的学生
select stu_name from exam_score where subject in('语文')
union
select stu_name from exam_score where subject in('数学') order by stu_name;

2.except(差集)

返回在第一张表出现,但在第二张表不存在的记录,两张表查询有先后顺序之别

-- 有语文成绩中没有数学成绩的
select stu_name from exam_score where subject in('语文')
except
select stu_name from exam_score where subject in('数学') order by stu_name;

3.intersect(交集)

-- 既有语文成绩又有数学成绩的学生
select stu_name from exam_score where subject in('语文')
intersect
select stu_name from exam_score where subject in('数学') order by stu_name;

交集也可以用平常用的inner join来替代