使用子查询和“HAVING”的极慢SQL查询

时间:2016-03-22 15:17:58

标签: mysql sql

我有这个查询,我想计算“user”中有多少条目在“usernames”中有多个条目

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

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

2 个答案:

答案 0 :(得分:0)

问题有点模糊,但试试这个:

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 (SELECT COUNT(*) where user_id = user.id from user_username) > 1

GROUP BY usernames.name
ORDER BY user.id DESC

我认为你不必按user_id分组以获得更多user_names的用户。

编辑我觉得这样更好。创建左外连接(您将获得多行重复user.id),然后按它们分组。

SELECT  user.id, COUNT(usernames.name) -- to show the number of usernames a user has 
FROM user 
LEFT JOIN user_username ON user.id = user_username.user_id
LEFT JOIN usernames     ON user_username.user_username_id = usernames.id
WHERE user.datecreated BETWEEN '2016-01-01' AND '2016-09-01'
GROUP BY user.id
HAVING COUNT(usernames.name) > 1
ORDER BY user.id DESC

旁注... userusernames.nameuser_username.user_iduser.iduser_username.user_username_idusernames.id,{{1}让我头晕......

答案 1 :(得分:0)

像这样帮助破解查询吗?

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