使用 JOIN 还是多次查表?关联查询效率哪种更高?

使用 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 的查询顺序如下:

  1. 找到满足 friendships_friendship.to_user_id = 1 条件的记录。
  2. 对找到的记录执行 join 操作,与 auth_user 表进行关联。

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享