MySQL GROUP BY…HAVING different values same field

时光总嘲笑我的痴心妄想 提交于 2019-12-04 13:41:50

Use

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

or

HAVING count(distinct ea.gender) = 2

BTW you should use a subquery to get all data when you group.

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 generally used with aggregate functions.

You should do self-jointo get the desired results, since ea.gender = 'female' AND ea.gender = 'male' is contradictory,which always returns empty set.

You can try this

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

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!