MySql Join 语法 性能 优化

联结的语法:

 ... from table1 inner|left|right join table2 on condition

内外联结的区别: 内联结将去除所有不符合条件condition的记录,外联结将保留部分不符合condition的记录;

               左联结将保留左边表table1的记录,此时右边表table2只返回符合condition的记录。

1,join概述

 ... from table1 inner|left|right join table2 on condition

inner join : 内联结,等值联结,取得两个表中符合condition的记录id。

left join : 左联结,取得table1的所有记录(table1中condition中的字段可能为空),和table2符合condition的记录,

right join : 右联结,取得table2的所有的记录(table2中condition中的字段可能为空),和table1符合condition的记录,

2,Inner join

内联结

  select * from A inner join B on A.mobile = B.mobile and andCondition;

将会返回 A.id 不为空,B.id 不为空,且A.mobile = B.mobile 和符合 andCondition的数据

3,left join

select * from A left join B on A.mobile = B.mobile and andCondition;

将会返回A的所有记录和 B.mobile = A.mobile的所有B的记录。

如果想取得A表中不满足condition的数据

select * from A

left join B on A.mobile = B.mobile 

where B.is is null

得到

用left join 模拟 inner join

  -> select * from A left join B on A.mobile = B.mobile where B.id is not null;

求A B 表中不符合condition条件的各自数据的集合

   -> select * from A left join B on A.mobile = B.mobile where B.id is null

    union

    select * from A right join B on A.mobile = B.mobile where A.id is null

得到差异数据(不符合condition的两个表的数据)

  

4,right join

-> select * from A right B on A.mobile = B.mobile ;

将得到B表的所有数据和A表中满足condition的数据

5,cross join

交叉联结,得到的是两个表的乘积

在mysql中(仅限mysql) cross join 和 inner join 的表现是一样的。在不指定on条件得到的都是笛卡尔积。

所以下面的三个语句效果一样

->...from A inner join B

->...from A cross join B

->...from A join B

6,full join

->  select * from A left join B on A.mobile = B.mobile;

  union

  select * from A right join B on A.mobile = B.mobile;

得到

7,性能优化

(1)显示inner join 和 隐式inner join

显示 --> select * from A inner join B on A.mobile = B.mobile;

隐式 --> select * from A inner join B where A.mobile = B.mobile;

10万数据的查询用时几乎相等。

(2)left join / right join 和 inner join

尽量用inner join 避免 外联结 和 null

在使用外联结的时候,如 -> select * from A left join B on A.mobile = B.mobile where whereCondition;

如果B中没有满足on condition的条件,则会产生一行所有列为null的数据。

  在 on condition 匹配阶段,where 条件不会被使用。在on condition结束后,where将会被使用,where条件将会从满足on condition的数据中再检索一次。

所以,在使用外联结市,我们要尽量给出尽可能多的匹配满足条件(即 on condition),减少where字句的检索。

不建议sql -> select * from A 

          left join B on A.mobile = B.mobile

          left join C on A.name = C.name

          where A.status = 1 and C.status = 1

建议的sql -> select * from A

          left join B on A.mobile = B.mobile and A.status = 1

          left join C on A.name = C.name and C.status = 1

尽量满足on condition,而少使用where的条件。

(3)on 条件 和 where 条件的不同

->select * from A left join B on A.mobile = B.mobile on A.name is not null;

将会返回A表的所有记录 和 B表中满足 (A.mobile = B.mobile on A.name is not null) 的记录;

->select * from A left join B on A.mobile = B.mobile where A.name is not null;

将会返回A表中所有记录 和 B表中满足 (A.mobile = B.mobile)的记录,然后 再通过where条件(A.name is not null)对结果进行筛选。

第一条sql语句返回的结果集条数 >= 第二条sql

(4)尽量避免子查询,而用join

原文地址:https://www.cnblogs.com/wangziqiang/p/5840308.html