sql中的三种表联结类型

来源:互联网 发布:补血产品网络推广 编辑:程序博客网 时间:2024/05/17 03:02

以下内容是我在网上学习之后整理出来的,有不对的地方欢迎指正,共同学习。


三种表联结类型分别是inner join,left join,right join 

1、名词解释:

(1)inner join :内联结 根据on关键字后面的匹配条件进行过滤,仅返回完全满足条件的记录;

(2)left join:左联结 以左表为基础,根据on来匹配右表,不仅返回完全匹配的记录,左表中不匹配的记录一并返回,只不过此时右表的字段会返回null;

(3)right join:右联结 以右表为基础 和左联结的执行过程类似。

2、举例

sql如下:

(1)select base.nip from base inner join credit on base.inp = credit.inp 

(2)select base.nip from base left join credit on base.inp = credit.inp 

(3)select base.nip from base right join credit on base.inp = credit.inp 


3、查询条件(这个很重要,使用的比较多)

三种联结都支持用where关键字来过滤,但有区别

inner join on可以代替where,也就是说左表的查询条件和右表的查询条件可以直接放在on后面;

left/right join单表(左表或右表)的查询条件必须用where,放在on后面无效;并且,left join中使用where时,where后面不能加右表的查询条件;right join同理;


举例如下:

(1)查询base表中status是ok并且credit表中flag是1的用户

select base.nip from base inner join credit on base.nip = credit.nip and base.status='ok' and credit.flag = '1'//and 是base表和credit表单独的查询条件,生效



(2)如果用left join会返回什么呢?

select base.nip from base left join credit on base.nip = credit.nip and base.status='ok' and credit.flag = '1'

返回结果与(2.2)的结果一致,因为and后面的查询条件不会生效


(3)能不能直接把上面sql中的on直接换成where?会返回什么?

先看一下直接换成where会返回什么

select base.nip from base left join credit on base.nip = credit.nip where base.status='ok' and credit.flag = '1'

返回结果与(3.1)一致,但是上面这条sql不应该存在,因为在左联结中加了右表的查询条件,左联结变得没有意义。


正确的sql:select base.nip from base left join credit on base.nip = credit.nip where base.status='ok' 

返回结果如下:ts3被where后的查询条件过滤


1 0