SQL - HAVING子句中的多行

时间:2012-04-30 11:51:26

标签: mysql sql database

好的,所以我想解决的问题是:

我想表达以下业务规则:

显示需要额外评论的组(针对特定教程(tutorialID)和周(周))。

所以基本上我需要确定一个组中的成员数量,然后我需要汇总该周和该组的所有scrum评论,并查看该数量是否等于该组中的成员数量。如果是,则表示所有成员已经过该周的审核,因此无需显示。

假设:会员每周只能进行一次评论。

我尝试了以下SQL,但是我收到以下错误Subquery returns more than 1 row

SELECT groupName, g.groupId
FROM `student` s, `group` g
WHERE s.GroupId = g.GroupId 
AND s.GroupId IS NOT NULL
AND s.tutorialId =  2
GROUP by s.GroupId
AND s.GroupID = (
    SELECT GroupId
    FROM student
    GROUP BY GroupId
    HAVING  count(*)> (
        SELECT count(*)
        FROM scrumreview r, student s
        WHERE r.reviewee = s.studentID
        GROUP BY GroupId    
        AND r.week = 5
        )
    )

学生 enter image description here

scrumreview enter asdasddescription here

enter image description here

3 个答案:

答案 0 :(得分:3)

您的内部查询(从第8行开始)返回多个groupid。等于运算符=比较1对1,但你想要的是比较1对多,你可以用IN进行比较。

因此,要解决此问题,请在第7行更改此代码...

AND s.GroupID = (

......对此:

AND s.GroupID IN (

答案 1 :(得分:0)

SELECT GroupId
FROM student
GROUP BY GroupId
HAVING  count(*)> (
    SELECT count(*)
    FROM scrumreview r, student s
    WHERE r.reviewee = s.studentID  
    AND r.week = 5
    )

返回多于1行,您需要优化该SQL以使其仅返回一行,或者您需要更改以下行:

AND s.GroupID = (

到IN:

AND s.GroupID IN (

答案 2 :(得分:0)

请改为尝试:

SELECT groupName, 
g.groupId FROM `student` s, 
`group` g WHERE s.GroupId = g.GroupId  
AND s.GroupId IS NOT NULL 
AND s.tutorialId =  2 
GROUP by s.GroupId AND s.GroupID in (SELECT GroupId FROM student GROUP BY GroupId 
HAVING  count(*)> (SELECT count(*) FROM scrumreview r, student s WHERE r.reviewee =
s.studentID AND r.week = 5))