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

心靈之曲
发布: 2024-11-06 21:27:02
原创
663人浏览过

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 操作。

以上就是MySQL JOIN 查询性能优化:获取用户粉丝信息,使用 JOIN 还是拆分查询更优?的详细内容,更多请关注php中文网其它相关文章!

数码产品性能查询
数码产品性能查询

该软件包括了市面上所有手机CPU,手机跑分情况,电脑CPU,电脑产品信息等等,方便需要大家查阅数码产品最新情况,了解产品特性,能够进行对比选择最具性价比的商品。

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号