关联查询.
-
关联查询又称为"联表查询"或"多表联查",关联查询分为:内连接、外连接和交叉连接(拓展)。
-
关联查询需要把多张表共有的字段作为关联查询的条件。
1.内连接-inner join/join.
-
内连接也叫自连接,这是我们经常用到的查询方式,内连接查询只能查询出多张表匹配的记录,匹配不上的记录时无法查询出来的 。内连接有以下三种写法:
select * from student s, color c where s.stuname = c.stuname;【简写方式】
select * from student s inner join color c on s.stuname = c.stuname;
select * from student s join color c on s.stuname = c.stuname;
2.外连接outer join.
-
外连接可进一步分为左外连接left outer join和右外连接right outer join,(简称左连接left join,右连接 right join);
2.1左外连接-left join.
-
连接就是以左边的表(left join 左边的表)为主表,即使有些记录关联不上,主表的信息也能全部查询出来,也就是左边的表数据全部展示,右边表的数据符合条件的展示,不符合条件的以空值代替。语法如下:
select * from student s left join color c on s.stuname = c.stuname;
select * from student s left outer join color c on s.stuname = c.stuname;
2.2右外连接-right join.
-
右连接就是以右边的表(right join 右边的表)为主表,即使有些记录关联不上,主表的信息也能全部查询出来,也就是右边的表数据全部展示,左边表的数据复合条件的展示,不符合条件的以空值代替。语法如下:
select * from student s right join color c on s.stuname = c.stuname;
select * from student s right outer join color c on s.stuname = c.stuname;
2.3全连接.
-
全连接的查询结果是左外连接和右外连接查询结果的并集,即使一些记录关联不上,也能够把部分信息查询出来。
第一种方式示例 (使用union有前提条件,列数要相同)
(select * from tb_user left join tb_shop on tb_user.shop_id = tb_shop.shop_id) #左连接两张表,没有取别名
union
(select * from tb_shop right join tb_user on tb_user.shop_id = tb_shop.shop_id)#右连接两张表,没有取别名
第二种方式示例
select * from tb_shop full join tb_user on tb_user.shop_id = tb_shop.shop_id
3.表之间数据的导入.
-
把某张表的结构数据导入到一张新表里面:create table 新表 as select 字段 from 旧表 where 成立的条件;
-
把某张表的结构导入到一张新表里面:create table 新表 as select 字段 from 旧表 where 不成立的条件(如:1=2,false,!true).
UNION合并.
-
前提条件:结果集列数个数相同,列的类型还要相同或是兼容;
-
使用场景:在项目统计报表模块,用来合并数据。
-
union:将所有的查询结果合并到一起,然后去除掉相同的记录,交集;
-
union all:将所有的查询结果合并到一起,不会去除掉系统的记录,并集。
-
案例:
select 'zs',20,sysdate
union
select 'zs',10,'2022-2-2'
union
select 'ls',10,'2022-2-2';
-
这样三行数据都不会合并,我们来改一下:
select 'zs',20,sysdate 测试 union select 'zs',10,'2022-2-2' union select 'ls',10,'2022-2-2';
-
这样第二行和第三行数据就会合并成一行,因为列的个数、值、类型都相同。
select 'zs',20,sysdate 测试
union all
select 'zs',10,'2022-2-2'
union all
select 'zs',10,2022-2-2';
-
这样第二行和第三行不会合并,即使满足合并条件,但是使用的是 union all。