使用多个子查询加速 mysql 查询
我想知道是否有一种方法可以加速由多个子查询排序的 mysql 查询。
在音乐相关网站上,用户可以喜欢不同的东西,例如艺术家、歌曲、专辑等。这些“喜欢”都存储在同一个表中。现在我想显示按用户朋友和所有用户的“喜欢”数量排序的艺术家列表。我想向所有艺术家展示,包括那些根本不喜欢的艺术家。
我有以下查询:
SELECT `artists`.*,
// friend likes
(SELECT COUNT(*)
FROM `likes`
WHERE like_type = 'artist'
AND like_id = artists.id
AND user_id IN (1,2,3,4, etc) // ids of friends
GROUP BY like_id
) AS `friend_likes`,
// all likes
(SELECT COUNT(*)
FROM `likes`
WHERE like_type = 'artist'
AND like_id = artists.id
GROUP BY like_id
) AS `all_likes`
FROM artists
ORDER BY
friend_likes DESC,
all_likes DESC,
artists.name ASC
在具有 2000 行的艺术家表上查询需要 ± 1.5 秒。恐怕随着桌子越来越大,这需要的时间也越来越长。我尝试使用 JOINS by 似乎无法正常工作,因为子查询包含 WHERE 语句。
任何正确方向的想法将不胜感激!
I'm wondering if there's a way to speed up a mysql query which is ordered by multiple subqueries.
On a music related site users can like different things like artists, songs, albums etc. These "likes" are all stored in the same table. Now I want to show a list of artists ordered by the number of "likes" by the users friends and all users. I want to show all artists, also those who have no likes at all.
I have the following query:
SELECT `artists`.*,
// friend likes
(SELECT COUNT(*)
FROM `likes`
WHERE like_type = 'artist'
AND like_id = artists.id
AND user_id IN (1,2,3,4, etc) // ids of friends
GROUP BY like_id
) AS `friend_likes`,
// all likes
(SELECT COUNT(*)
FROM `likes`
WHERE like_type = 'artist'
AND like_id = artists.id
GROUP BY like_id
) AS `all_likes`
FROM artists
ORDER BY
friend_likes DESC,
all_likes DESC,
artists.name ASC
The query takes ± 1.5 seconds on an artist table with 2000 rows. I'm afraid that this takes longer and longer as the table gets bigger and bigger. I tried using JOINS by can't seem to get this working because the subqueries contain WHERE statements.
Any ideas in the right direction would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用 JOIN 而不是子查询:
如果这不能使查询更快,请尝试添加索引,或考虑选择更少的字段。
Try using
JOIN
s instead of subqueries:If this doesn't make the query faster, try adding indices, or consider selecting less fields.
你需要稍微分解一下,看看时间都花在哪里了。你说得对,2000 行的 1.5 秒无法很好地扩展。我怀疑您需要查看索引和外键关系。单独查看每个计数/分组查询,尽可能调整它们,然后重新组合。
You need to break this down a bit to see where the time goes. You're absolutely right that 1.5 sec on 2000 rows won't scale well. I suspect you need to look at indexes and foreign-key relationships. Look at each count/group-by query individually to get them tuned as best you can then recombine.
尝试使用内联 IF() 汇总到查询中并遍历表/连接一次
try rolling up into a query using inline IF() and go through the table/join ONCE