I want to use a query similar to the following to retrieve all rows in events
that have at least one corresponding event_attendances
row for 'male'
and 'female'
. The below query returns no rows (where there certainly are some events
that have event_attendances
from both genders).
Is there a way to do this without a subquery (due to the way the SQL is being generated in my application, a subquery would be considerably more difficult for me to implement)?
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
generally used with aggregate functions.You should do
self-join
to get the desired results, sinceea.gender = 'female' AND ea.gender = 'male'
is contradictory,which always returns empty set.You can try this
Hope this helps.
Use
or
BTW you should use a subquery to get all data when you group.