1、定义与区别
内连接 :找出两个表存在连接关系的字段,符合连接关系的数据
外连接:找出不匹配的项
2、内连接
2.1、隐式内连接
定义:内连接未出现inner join等关键字
语法:select 表1.字段名,表n.字段名 from 表1 where 条件
示例
准备两张表:user 和 goods表 如图
可以发现两张表存在连接关系,user.gid 和 goods.id
问题:查询出哪些用户购买过商品并显示购买商品名称
select user.username, goods.name from user,goods where user.gid = goods.id
2.2、显式内连接
定义:出现了inner join的内连接
语法:select 表1.字段名,表n.字段名 from 表1 inner join 表n on 条件
问题:查询出哪些用户购买过商品并显示购买商品名称
select user.username,goods.name from user inner join goods on user.gid = goods.id
3、外连接
3.1、左外连接
定义:左外连接会把左表所有数据查询出来,右表符合连接条件的数据查询出来
语法:select 表1.字段名,表n.字段名 from 表1 left join 表n on 条件
示例:查询所有用户购买过哪些商品 并将商品信息展示出来
select * from user left join goods on user.gid = goods.id
3.2、右外连接
定义:右外连接会把右表所有数据查询出来,左表符合连接条件的数据查询出来
语法:select 表1.字段名,表n.字段名 from 表1 right join 表n on 条件
示例:查询哪些商品被用户购买过
select * from user right join goods on user.gid = goods.id
4、子查询
语法:select 字段名 from 表 where 字段 in (子查询语句)
示例:将购买过商品的用户信息展示出来
select * from user where gid in (select id from goods)
5、注意
- 内连接里显式跟隐式的结果是一样的
- 显式内连接里inner可以省略
- 内连接里from后跟表的顺序无所谓 先from哪张表结果都是一样的