模型关联查询查询与 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 分析,所以请大家指点一下!

希望大佬们能指点一下在实际的开发中应该使用那种查询方法...

本人小白,如果有地方撰写的不对,还行大佬勿喷....

DaiChongWeb
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 2
qiuyuhome

mark

5年前 评论
daichongweb (楼主) 5年前
qiuyuhome (作者) 5年前

这个问题社区早就讨论过了的,数据量大的时候推荐使用 join,数据小用关联

5年前 评论
daichongweb (楼主) 5年前
daichongweb (楼主) 5年前