MySQL AND alternative for each table in a join
I have a simple join in a query however I need to have a condition on both of the tables "confirmed='yes'" but if one of the tables doesn't have any that match the query returns with no rows.
Database:
.----------parties----------.
| id - party_id - confirmed |
|---------------------------|
| 1 1 yes |
| 1 2 no |
| 1 3 no |
+---------------------------+
.-----------events----------.
| id - event_id - confirmed |
|---------------------------|
| 1 1 no |
+---------------------------+
or
.----------parties----------.
| id - party_id - confirmed |
|---------------------------|
| 1 1 no |
| 1 2 no |
| 1 3 no |
+---------------------------+
.-----------events----------.
| id - event_id - confirmed |
|---------------------------|
| 1 1 yes |
+---------------------------+
Query:
SELECT p.party_id, e.event_id
FROM parties p
LEFT JOIN events e
ON p.id=e.id
WHERE p.id = '1'
AND p.party_id IN (1,2,3)
AND e.event_id IN (1)
AND p.confirmed='yes'
AND e.confirmed='yes'
It returns nothing but I want it to return party_id 1 with a empty event_id or event_id and a empty party_id. I hope this make sense and I not missing anything, Thanks for your help!
EDIT Added reverse database code that I need to return the event_id and a empty party_id开发者_开发知识库
Your WHERE
conditions filters out all NULLs
generated by the LEFT JOIN
.
Move all conditions that involve events
into the ON
clause:
SELECT p.party_id, e.event_id
FROM parties p
LEFT JOIN
events e
ON e.id = p.id
AND e.event_id IN (1)
AND e.confirmed = 'yes'
WHERE p.id = '1'
AND p.party_id IN (1, 2, 3)
AND p.confirmed = 'yes'
UNION ALL
SELECT p.party_id, e.event_id
FROM events e
LEFT JOIN
parties p
ON p.id = e.id
AND p.party_id IN (1, 2, 3)
AND p.confirmed = 'yes'
WHERE e.event_id IN (1)
AND e.confirmed = 'yes'
AND p.id IS NULL
精彩评论