gpt4 book ai didi

Mysql查询: fastest way to find users followed by or following another user

转载 作者:行者123 更新时间:2023-11-29 12:19:33 25 4
gpt4 key购买 nike

我有下表:

关系

idfollower_idfollowee_id状态

用户

id姓名电子邮件

我想查找正在关注或被特定用户关注的所有用户。

这是我到目前为止所拥有的,但速度非常慢:

SELECT DISTINCT
`users`.*
FROM
`users`
INNER JOIN
`relationships` ON ((`users`.`id` = `relationships`.`follower_id`
AND `relationships`.`followee_id` = 1)
OR (`users`.`id` = `relationships`.`followee_id`
AND `relationships`.`follower_id` = 1))
WHERE
`relationships`.`status` = 'following'
ORDER BY `users`.`id`

我所说的慢是什么意思

我有一个用户,大约有 600 个关注者和 600 个关注者,此查询运行大约需要 5 秒,对于这些数字来说,这似乎非常慢!

explain 方法显示以下内容:

+----+-------------+---------------+------+-----------------------------------------------------------------------+------+---------+------+------+------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------------+------+-----------------------------------------------------------------------+------+---------+------+------+------------------------------------------------+
| 1 | SIMPLE | relationships | ALL | index_relationships_on_followed_id,index_relationships_on_follower_id | NULL | NULL | NULL | 727 | Using where; Using temporary; Using filesort |
| 1 | SIMPLE | users | ALL | PRIMARY | NULL | NULL | NULL | 767 | Range checked for each record (index map: 0x1) |
+----+-------------+---------------+------+-----------------------------------------------------------------------+------+---------+------+------+------------------------------------------------+

最佳答案

尝试使用union将其分成两个查询:

SELECT u.*
FROM `users` u INNER JOIN
`relationships` r
ON u.`id` = r.`follower_id` AND r.`followee_id` = 1
WHERE `r.`status` = 'following'
UNION
SELECT u.*
FROM `users` u INNER JOIN
`relationships` r
ON u.`id` = r.`followee_id` AND r.`follower_id` = 1
WHERE `r.`status` = 'following'
ORDER BY id;

这可能是更复杂的查询具有更好性能的情况。这些查询还将受益于索引:relationships(status, follower_id, followee_id)relationships(status, followee_id, follower_id)

关于Mysql查询: fastest way to find users followed by or following another user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29240791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com