Mysql计数并返回一行数据

时间:2015-06-17 13:20:27

标签: 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 ::错误:选择的嵌套程度太高”

如果没有额外的子查询,有没有办法做到这一点?

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

3 个答案:

答案 0 :(得分:0)

请给这个查询一个拍摄

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查询和表格定义以及更好的问题说明。

我希望这会有所帮助

答案 1 :(得分:0)

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

textColor

答案 2 :(得分:0)

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

select id, count(*) from users group by id很好

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

关于您的查询,我认为不需要指向用户表的链接。只使用外键应该没问题。

试试这个:

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)