什么是多表关联查询定义:查询数据来源于多张表
有时候查询的数据需要从2个表或者更多的表中提取,这个时候就需要使用多表关联查询多表查询
主要讲:1.内连接 2.左连接(左外连接) 3.右连接(右外连接) 4、全连接(全外连接)
表字段:
dept表:部门表
dept1 部门编号
dept_name 部门名称
emp表: 员工表
sid 员工编号
name 姓名
age 年龄
woektime_start 入职时间
incoming 工资
dept2 部门编号
1、笛卡尔积查询
两张表相乘得到的结果:
左边有m条记录,右边有n条记录,查询出来的结果就是m*n,(这种查询包含大量的错误结果,通常不会使用这种查询)
select * from 表1,表2 ;
什么是左连接和右连接:左连接和右连接都属于外连接。如果左表的某行在右表没有匹配行,则在相关联的结果集行中右表的所有选择列表均为空值
内连接:也称等值连接,返回两张表都满足条件的部分
2、内连接 (普通内连接,隐藏内连接)
查询两个表共有的关联的数据
普通内连接: select * from 表1 inner join 表2 on 表1.关联字段=表2.关联字段;
隐藏内连接:select * from 表1,表2 where 表1.关联字段=表2.关联字段
左连接:select * from 表 1 left join 表 2 on 表1.关联子段=表2.关联字段
右连接:select * from 表1 right join 表2 on 表1.关联字段=表2.关联字段
左表独有的数据:select * from 表1 left join 表2 on 表1.关联字=表2.关联字段 where 右表的字段is null 左表独有数据(先左连接,再右连接,是以右表的字段为空的值显示出来)
左表和右表独有的数据:union
select * from 表1 right join 表2 on表1.关联字=表2.关联字 where 左表的字段is null
union
select * from 表1 left join 表2 on 表1.关联字=表2关联字 where 右表的字段is null
全外连接:
方法一:内连接+左右独有
select * from 表1,表2 where 表1.关联字=表2.关联字
union
select * from 表1 left join 表2 on 表1.关联字=表2.关联字 where 右表字段 is null
union
select * from 表1 right join 表2 on 表1.关键字=表2.关联字 where 左表字段is null
方法二:左连接+右独有数据
select * from 表1 left join 表2 on 表1. 关联字=表2.关联字
union
select * from 表1 right join 表2 on 表1.关键字=表2.关键字 where 左表字段 is null
方法三:右连接+左独有的数据
select * from 表1 right join 表2 on 表1.关联字=表2.关联字
union
select * from 表1 left join 表2 on 表1.关联字=表2.关联字 where 左连接 is null
更新语句:
drop table dept ;
drop table emp ;
select * from emp ;
select * from dept;