Mysql count 和 return 只是一行数据

Mysql count and return just one row of data

我需要计算已回答所有这 3 个 profile_options 的用户数量(因此他们在 profile_answers table 中至少有 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

问题是这个查询是 return 一个 table,每个用户都有行,他们回答了多少(在这种情况下总是 3)。我需要的是 return 仅包含用户总数的一行(因此本例中所有行的总和)

我知道如何用另一个子查询来做,但问题是我 运行 进入 "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

如果您的 table 中有大量数据,您将通过像这样使用临时 table 获得 better/faster 性能

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

除非有必要加入userstable可以这样

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 查询和 table 定义以及更好的问题描述。

希望对您有所帮助

您可以使用 AS 子句为查询命名。请参阅下面的更新查询。

SELECT SUM(sum_sub.users_count) FROM (
(SELECT COUNT(DISTINCT(users.id)) as 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)
) as sum_sub

您不应在 select 语句中不存在的字段上分组。

select id, count(*) from users group by id 可以

select count(id) from users group by id 不是

关于您的查询,我认为 link 用户 table 没有必要。只用外键应该没问题。

试试这个:

select count(*) from 
(SELECT users_id count(*) as cnt
FROM profile_answers
INNER JOIN users ON profile_answers.user_id = users.id
WHERE profile_answers.profile_option_id IN (37,86,102) 
group by users_id
having count(*) >3)