mysqljoin与crossjoin效率_MySqlJoin语法性能优化联结的语法:
... 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 bile = B.mobile and andCondition;
将会返回 A.id 不为空,B.id 不为空,且A.mobile = B.mobile 和符合 andCondition的数据
3,left join
select * from A left join B bile = B.mobile and andCondition;
将会返回A的所有记录和 B.mobile = A.mobile的所有B的记录。
如果想取得A表中不满⾜condition的数据
select * from A
left join B bile = B.mobile
where B.is is null
得到
⽤left join 模拟 inner join
-> select * from A left join B bile = B.mobile where B.id is not null;
求A B 表中不符合condition条件的各⾃数据的集合
-> select * from A left join B bile = B.mobile where B.id is null
union
select * from A right join B bile = B.mobile where A.id is null
得到差异数据(不符合condition的两个表的数据)
4,right join
-> select * from A right B bile = 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 bile = B.mobile;
union
select * from A right join B bile = B.mobile;多表left join
得到
7,性能优化
(1)显⽰inner join 和 隐式inner join
显⽰ --> select * from A inner join B bile = B.mobile;
隐式 --> select * from A inner join B bile = B.mobile;
10万数据的查询⽤时⼏乎相等。
(2)left join / right join 和 inner join
尽量⽤inner join 避免 外联结 和 null
在使⽤外联结的时候,如 -> select * from A left join B bile = 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 bile = 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 bile = 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 bile = 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 bile = B.mobile where A.name is not null;
将会返回A表中所有记录 和 B表中满⾜ (A.mobile = B.mobile)的记录,然后 再通过where条件(A.name is not null)对结果进⾏筛选。第⼀条sql语句返回的结果集条数 >= 第⼆条sql
(4)尽量避免⼦查询,⽽⽤join
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论