今天有一个需求,我有三张表,一张学生表,一张教师表,一样辅导员。
它们都有编号,都有密码,但是字段名不一样,我想一次查询出三张表里面这些编号和密码放在一个查询结果集里面!
我们可以编写三个SQL语句,使用union
关键字把查询结果拼接起来。
比如我们单独查询是这样的:
select st_id id,st_password passordfrom gb_student;select tea_id id,tea_password passordfrom gb_teacher;select te_id id,te_password passordfrom gb_counselor;
这是三个结果集,我想把它合成一个,这么用
select id, passwordfrom(select tea_id id,tea_password passwordfrom gb_teacherunionselect st_id,st_passwordfrom gb_studentunionselect te_id,te_passwordfrom gb_counselor) t;<!--外面用一个select包起来的目的是为了在后边可以加where进行条件判断 ,注意t这个别名不能少-->
完美啊!
总结一下:
除了union
可以把多个查询sql的结果集拼接起来,还有一个union all
这两个的区别是:
union
是取交集,也就是去除相同的结果,保留一个。union all
是取并集,也就是可能会有相同的结果。