-4

我有两个表:“成员”和“问题”。每个成员可以提出多个问题。

我想检索被问到超过 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
)

我可以做些什么来改进这个查询?谢谢

4

2 回答 2

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
于 2012-09-06T14:21:16.493 回答
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

正如您在这种情况下看到的那样ON a.member_id = b.member_id,它通过链接两个表memberID您可以自由地将 columnName 更改为表上存在的名称。

于 2012-09-06T14:23:46.783 回答