关联查询:使用 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 的查询顺序如下:
以上就是使用 JOIN 还是多次查表?关联查询效率哪种更高?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号