MySQL GROUP BY ...具有不同的值相同的字段

时间:2015-11-11 09:48:39

标签: mysql join group-by having

我想使用类似于以下内容的查询来检索eventsevent_attendances'male'至少有一个'female'行的所有行。以下查询不返回任何行(其中某些events肯定有来自两个性别的event_attendances

有没有办法在没有子查询的情况下执行此操作(由于在我的应用程序中生成SQL的方式,子查询对我来说实现起来要困难得多)?

SELECT * FROM events e
LEFT JOIN event_attendances ea ON (e.id = ea.event_id)
GROUP BY e.id
HAVING ea.gender = 'female' AND ea.gender = 'male'

2 个答案:

答案 0 :(得分:6)

使用

HAVING sum(ea.gender = 'female') > 0 
   AND sum(ea.gender = 'male') > 0

HAVING count(distinct ea.gender) = 2

顺便说一句,你应该使用子查询来获取分组时的所有数据。

SELECT * 
FROM events
where id in
(
    SELECT events.id 
    FROM events
    LEFT JOIN event_attendances ON (events.id = event_attendances.event_id)
    GROUP BY events.id
    HAVING count(distinct event_attendances.gender) = 2
)

答案 1 :(得分:0)

HAVING通常与聚合函数一起使用。

你应该self-join来获得所需的结果,因为ea.gender = 'female' AND ea.gender = 'male'是矛盾的,它总是返回空集。

你可以试试这个

SELECT T1.* 
FROM events T1 
INNER JOIN 
(SELECT events.id 
    FROM events
    LEFT JOIN event_attendances ON (events.id = event_attendances.event_id)
    GROUP BY events.id
    HAVING COUNT(DISTINCT event_attendances.gender) = 2) T2 ON T1.events.id=T1.events.id

希望这有帮助。