views:

30

answers:

1

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

+2  A: 

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
Quassnoi
Thanks for the answer, it works but it there a way to get it to work in reverse? I.E. all of parties confirmed = no and events confirmed = yes
Scott
@Scott: please update your question with a sample dataset and the desired output.
Quassnoi
I added it to the question, thanks for your help!
Scott
@Scott: see the post update.
Quassnoi
Thanks for the help, BTW the last line "AND p.is IS NULL" needs to be "AND p.id IS NULL"
Scott