使用 JOIN 还是多次查表?关联查询效率哪种更高?
你在学习相关的知识吗?本文,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!
关联查询:使用 join 还是多次查表?
需求:获取某个人的粉丝信息
表结构:
create table `auth_user` (...); create table `friendships_friendship` (...);
两种方式:
方式一:使用 join
select ... from `friendships_friendship` left join `auth_user` t3 on ( `friendships_friendship`.`from_user_id` = t3.`id` ) where `friendships_friendship`.`to_user_id` = 1;
方式二:拆分成两次查表
第一次获取 id
select ... from `friendships_friendship` where `friendships_friendship`.`to_user_id` = 1;
第二次使用 id 查询
SELECT ... FROM `auth_user` WHERE `auth_user`.`id` IN (...);
效率对比:
第一种方式效率更高,因为它只执行了一次查询,而第二种方式需要执行两次查询。虽然第一种方式使用了 join 操作,但在 mysql 中,join 仅对满足查询条件的记录执行。因此,与第二种方式使用 in 操作符相比,不会有太大的性能差异。
查询顺序:
对于方式一,mysql 的查询顺序如下:
- 找到满足 friendships_friendship.to_user_id = 1 条件的记录。
- 对找到的记录执行 join 操作,与 auth_user 表进行关联。
好了,本文到此结束,带大家了解了《使用 JOIN 还是多次查表?关联查询效率哪种更高?》,希望本文对你有所帮助!关注主机宝贝公众号,给大家分享更多数据库知识!