MySql Join 语法 性能 优化

联结的语法:mysql

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

内外联结的区别: 内联结将去除全部不符合条件condition的记录,外联结将保留部分不符合condition的记录;性能优化

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

1,join概述优化

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

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

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

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

2,Inner joinmobile

内联结

  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

相关文章
相关标签/搜索