我需要计算已回答所有这 3 个 profile_options 的用户数量(因此他们在 profile_answers 表中至少有 3 条记录)。
SELECT COUNT(DISTINCT(users.id)) users_count
FROM users
INNER JOIN profile_answers ON profile_answers.user_id = users.id
WHERE profile_answers.profile_option_id IN (37,86,102)
GROUP BY users.id
HAVING COUNT(DISTINCT(profile_answers.id))>=3
问题是这个查询返回一个表,其中包含每个用户的行以及他们回答的数量(在本例中始终为 3)。我需要的是仅返回包含用户总数的一行(因此是本示例中所有行的总和)
我知道如何使用另一个子查询来做到这一点,但问题是我遇到了“Mysql::Error: Too high level of Nesting for select”
有没有办法在没有额外子查询的情况下做到这一点?
SELECT SUM(sum_sub.users_count) FROM (
(SELECT COUNT(DISTINCT(users.id)) users_count
FROM users
INNER JOIN profile_answers ON profile_answers.user_id = users.id
WHERE profile_answers.profile_option_id IN (37,86,102)
GROUP BY users.id
HAVING COUNT(DISTINCT(profile_answers.id))>=3)
) sum_sub
最佳答案
请尝试一下此查询
SELECT COUNT(DISTINCT(u.id)) AS users_count
FROM users AS u
INNER JOIN (
SELECT user_id, COUNT(DISTINCT profile_option_id) AS total
FROM profile_answers
WHERE profile_option_id IN (37,86,102)
GROUP BY users.id
HAVING COUNT(DISTINCT profile_option_id) = 3
) AS a ON a.user_id = u.id
如果表中有大量数据,通过使用这样的临时表将获得更好/更快的性能
CREATE TEMPORARY TABLE a (KEY(user_id)) ENGINE = MEMORY
SELECT user_id, COUNT(DISTINCT profile_option_id) AS total
FROM profile_answers
WHERE profile_option_id IN (37,86,102)
GROUP BY users.id
HAVING COUNT(DISTINCT profile_option_id) = 3;
那么你的最终查询将如下所示
SELECT COUNT(DISTINCT(u.id)) as users_count
FROM a
INNER JOIN on a.user_id = u.id
除非需要加入users
表,否则你可以使用这个
SELECT COUNT(*) AS users_count
FROM (
SELECT user_id, COUNT(DISTINCT profile_option_id) AS total
FROM profile_answers
WHERE profile_option_id IN (37,86,102)
GROUP BY users.id
HAVING COUNT(DISTINCT profile_option_id) = 3
) AS a
如果您需要其他解决方案,请考虑向我们提供查询和表定义的EXPLAIN EXTENDED
以及更好的问题描述。
希望这有帮助
关于Mysql统计并只返回一行数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30892876/