模型关联查询查询与 left join 查询的效率对比
初学Laravel
最近接手一个新项目,整个项目完全看不到left join
这样的写法,我打印了模型关联查询后的sql
后发现跟常有的查询写法完全不同。
原谅我一直是个码农,几乎没见过这样的写法,一直想对比一下这样的写法和常用的写法性能方面到底有什么差别。
一个小栗子
模型关联生成的sql
select * from `comment` where exists (select * from `post_comment` where `comment`.`id` = `post_comment`.`comment_id` and `post_id` = ?)
常用查询
SELECT `comment`.id,`comment`.info,`comment`.user_id from `comment` left join post_comment on `comment`.id = `post_comment`.comment_id where post_comment.post_id = ?
单从sql
上看区别还是挺大的,再做码农的期间,最常听到的就是链表查询性能不好。但是还真不能确定这两个sql
到底哪个性能好一点,没办法只能测试一下。
posts Tables
id | title | time |
---|---|---|
1 | 模型关联查询 | 2019-11-08 |
2 | left join 查询 | 2019-11-08 |
comment Tables
id | info | time |
---|---|---|
1 | 模型关联查询的性能好 | 2019-11-08 |
2 | left join 查询的性能好 | 2019-11-08 |
3 | 两个都挺好 | 2019-11-08 |
post_comment Tables
id | post_id | comment_id |
---|---|---|
1 | 1 | 1 |
2 | 2 | 2 |
3 | 3 | 2 |
为了避免争议,我添加了一些比较合理的数据。
数据量
posts | comment | post_comment |
---|---|---|
29999条 | 29999条 | 29999条 |
下面使用EXPLAIN进行分析
EXPLAIN select * from `comment` where exists (select * from `post_comment` where `comment`.`id` = `post_comment`.`comment_id` and `post_id` = 2)
id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
---|---|---|---|---|---|---|---|---|---|---|---|
1 | PRIMARY | comment | NULL | ALL | NULL | NULL | NULL | NULL | 29999 | 100.00 | Using where |
2 | DEPENDENT SUBQUERY | post_comment | NULL | ref | post_id,comment_id | post_id | 5 | const | 1 | 10.00 | Using where |
EXPLAIN SELECT `comment`.id,`comment`.info,`comment`.user_id from `comment` left join post_comment on `comment`.id = `post_comment`.comment_id where post_comment.post_id = 2
id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
---|---|---|---|---|---|---|---|---|---|---|---|
1 | SIMPLE | post_comment | NULL | ref | post_id,comment_id | post_id | 5 | const | 1 | 100.00 | Using where |
2 | SIMPLE | comment | NULL | eq_ref | PRIMARY | PRIMARY | 4 | test.post_comment.comment_id | 1 | 100.00 | NULL |
在我的理解里,我觉得是left join的性能好一些,因为不是很懂sql
分析,所以请大家指点一下!
希望大佬们能指点一下在实际的开发中应该使用那种查询方法...
本人小白,如果有地方撰写的不对,还行大佬勿喷....
mark
这个问题社区早就讨论过了的,数据量大的时候推荐使用join,数据小用关联