Mysql统计并只返回一行数据

标签 mysql join count subquery having

我需要计算已回答所有这 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/

相关文章:

MySQL JOINS 不带 where 子句

mysql - 如何在 MySQL 中插入特殊字符,例如 '?

jpa - 如何使用 JPA 2.1 CriteriaDelete 从连接表中删除实体

MySQL连接查询帮助

python - 在Python中,如何计算电子邮件地址列表中 '1'的数量?

R编程——统计某一范围内数字的出现次数

MySQL 1292 不正确的日期时间值

mysql - 查找参加完全相同类(class) SQL 的学生列表

mysql - 在 MySQL 的同一个表中查找具有相似属性的条目

postgresql - PostgreSQL 计数查询优化