gpt4 book ai didi

mysql - 带有子查询和 "HAVING"的极慢 SQL 查询

转载 作者:可可西里 更新时间:2023-11-01 07:43:56 26 4
gpt4 key购买 nike

我有这个查询,我想计算“用户”中有多少条目在“用户名”中有多个条目

SELECT usernames.NAME,
COUNT(user.id)
FROM user
INNER JOIN user_username ON user.id = user_username.user_id
INNER JOIN usernames ON user_username.user_username_id = usernames.id
WHERE
user.datecreated BETWEEN '2016-01-01' AND '2016-09-01'
AND user.id IN
(
SELECT user_id
FROM user_username
GROUP BY user_id
HAVING COUNT(*) > 1
)
GROUP BY usernames.NAME
ORDER BY user.id DESC

查询有效,但速度太慢,有什么想法可以加快查询速度吗?

最佳答案

像这样分解查询有帮助吗?

CREATE TEMPORARY TABLE QualifiedUserIDs AS (
SELECT user_id
FROM user_username
GROUP BY user_id
HAVING COUNT(*) > 1);

SELECT usernames.NAME,
COUNT(user.id)
FROM user
INNER JOIN QualifiedUserIDs quids ON quids.user_id = user.id
INNER JOIN user_username ON user.id = user_username.user_id
INNER JOIN usernames ON user_username.user_username_id = usernames.id
WHERE
user.datecreated BETWEEN '2016-01-01' AND '2016-09-01'

GROUP BY usernames.NAME
ORDER BY user.id DESC

关于mysql - 带有子查询和 "HAVING"的极慢 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36158330/

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