模型关联查询查询与 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
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 2
qiuyuhome

mark

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

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

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

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!