我有两张桌子:“会员”和“问题”。每个成员都可以提出多个问题。
我想检索被问过3个以上问题的成员数
到目前为止我的查询:
SELECT DISTINCT q.question_id, COUNT( q.question_id ) AS question_id_count
FROM member m
inner join question q on m.member_id = q.member_id
GROUP BY m.member_id
HAVING (
COUNT( q.question_id ) >3
)
如何改善此查询?谢谢
答案 0 :(得分:2)
这是不正确的。
如果您按成员进行分组,则应显示成员!
distinct
是不必要的,每个成员只会显示一次(除非你有重复的成员!)
考虑此评论:
您想要检索要求超过3的成员数量吗? 问题或每个成员要求更多问题的问题 超过3个问题?
第一个选项是
select count(*) from
(SELECT m.member_id
FROM member m
inner join question q on m.member_id = q.member_id
GROUP BY m.member_id
HAVING COUNT(q.question_id) >3) T
第二个选项是
SELECT m.member_id, COUNT( q.question_id ) AS question_id_count
FROM member m
inner join question q on m.member_id = q.member_id
GROUP BY m.member_id
HAVING COUNT(q.question_id) >3
答案 1 :(得分:0)
根据您的声明i want to retrieve count of member whose asked
more than 3 question
,加入表格并按memberID
分组。
SELECT a.member_id, count(b.member_id) totalQuestion
FROM member a
INNER JOIN question b
ON a.member_id = b.member_id
GROUP BY a.member_id
HAVING count(b.member_id) > 3
正如您在此条件{$ 1}}上看到的那样,它通过ON a.member_id = b.member_id
链接两个表格(您可以自由地将columnName更改为您桌面上存在的名称。)