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

MySQL GROUP BY...HAVING different values same field

我想使用类似于以下的查询来检索 events 中至少有一个对应 'male''female' 行的所有行。下面的查询 returns 没有行(肯定有一些 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'

使用

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
)

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

你应该self-join得到想要的结果,因为ea.gender = 'female' AND ea.gender = 'male'是矛盾的,总是returns空集。

你可以试试这个

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

希望对您有所帮助。