I have two tables, Foo and Bar, I’d like to join them together so BarID gets the prize based on having a key that is in the array, or if there’s no array set up, it defaults as if every key unlocks the prize.
>Table Foo
fooID | someArray | prize
----------------------------------
1 | {10,20,30} | 'Winner'
2 | {10} | 'Grand prize'
3 | null | 'Participant'
(That’s not a string for someArray, it’s a valid postgresql type.)
>Table Bar
BarID | Key
------------
1 | 10
2 | 20
3 | 30
4 | 40
5 | 40
6 | 40
I’ve tried this below:
SELECT
Foo.fooID,
Bar.prize
FROM Foo
LEFT JOIN Bar ON Bar.Key = ANY(someArray)
I have minimal success with this, when I put in a WHERE clause such as
WHERE Bar.BarID = 3
My results are simply ‘Winner’m but I also want to get ‘Participant’. If I set up my WHERE to include nulls:
WHERE
Bar.BarID = 3
OR
Foo.someArray = null
I still do not get my null values out.
No where clause returns all combinations of values, including the nulls.
I’m not really sure how to get this behaviour I want. I can get all, or I can get just one set of values, but not both.
To give examples, if I were to do the join for BarID = 1, I should get “Winner”, “Grand prize” and “participant”. If I were to select for BarID 5, I would only get Participant.
Try:
The equality operator always yields
NULL, notTRUEwhen applied to aNULLvalue. To test a column whether it holds theNULLvalue, you need the above expression, not.Foo.someArray = NULLMore about that in the manual.
You also have to put it in your
JOINcondition, not in aWHEREclause, as @Michael commented. Like:If you put it in the
WHEREclause, you might also find rows whereFoo.someArray IS NOT NULL, but has different prizes. With aLEFT JOIN, if (and only if) no row is found inFoofor a givenBar,NULLvalues will be appended for all columns ofFoo, includingsomeArray. This would fool a check forNULLin aWHEREcondition.