MySQL JOIN 查询性能优化:获取用户粉丝信息,使用 JOIN 还是拆分查询更优?

MySQL JOIN 查询性能优化:获取用户粉丝信息,使用 JOIN 还是拆分查询更优?

mysql join 查询性能优化:使用 join 还是拆分查询?

对于获取特定用户的粉丝信息的查询,可以使用 join 操作或拆分查询。以下分析对比了两种方法的性能:

join 查询 (方式一)

select     `friendships_friendship`.`id`,     `friendships_friendship`.`from_user_id`,     `friendships_friendship`.`to_user_id`,     `friendships_friendship`.`created_at`,     t3.`id`,     t3.`password`,     t3.`last_login`,     t3.`is_superuser`,     t3.`username`,     t3.`first_name`,     t3.`last_name`,     t3.`email`,     t3.`is_staff`,     t3.`is_active`,     t3.`date_joined` from     `friendships_friendship`     left outer join `auth_user` t3 on (         `friendships_friendship`.`from_user_id` = t3.`id`     ) where     `friendships_friendship`.`to_user_id` = 1 limit     21;

join 查询仅执行了一次查询,虽然使用了连接操作,但只连接了满足条件的记录。因此,整体效率不会比拆分查询差多少。

拆分查询 (方式二)

此方法分为两步:

步骤 1: 获取好友关系表中满足条件的记录。

select     `friendships_friendship`.`id`,     `friendships_friendship`.`from_user_id`,     `friendships_friendship`.`to_user_id`,     `friendships_friendship`.`created_at` from     `friendships_friendship` where     `friendships_friendship`.`to_user_id` = 1 limit     21;

步骤 2: 使用步骤 1 获得的 from_user_id,在用户表中查询用户信息。

SELECT     T3.`id`,     T3.`password`,     T3.`last_login`,     T3.`is_superuser`,     T3.`username`,     T3.`first_name`,     T3.`last_name`,     T3.`email`,     T3.`is_staff`,     T3.`is_active`,     T3.`date_joined` FROM     `auth_user` T3 WHERE     T3.`from_user_id` in (xxxx, xxx, xxxx) LIMIT     21;

拆分查询分两步进行,需要分别执行两次查询,效率稍低。

总的来说,对于这种类型的查询,使用 join 查询的效率会略高于拆分查询。

mysql 执行顺序

mysql 的执行顺序是先执行 where 子句,然后再执行 join 操作。因此,对于方式一的查询,mysql 会先找到 friendships_friendship 表中 to_user_id=1 的记录,再与 auth_user 表进行 join 操作。

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