user249850
user249850

Reputation: 1

SQL query: return specific value in 2nd table, else return NULL

I'm trying to make a join on 2 tables - let's call them CAT and DRINK. What I'm trying to do is return only a specific "Type" from the DRINK table, else return NULL for that table. That said, I still want all rows from my CAT table.

So if the type of drink I'm trying to return is "Milk", the result of my query: -

Garfield    | Milk 
Tom         | Milk 
Hello Kitty | NULL

In the above example, Garfield and Tom have "Milk" in the DRINK table (they might also have some other values, like "Wine" or "Beer") and Hello Kitty does not have "Milk" (hence the NULL).

I've been trying to solve this doing some UNION or UNION ALL queries combined with a WHERE on "Type" (am I on the right path here?) but have had no luck.

Would anybody please be able to point me in the right direction?

Thanks.

Upvotes: 0

Views: 73

Answers (1)

Lamak
Lamak

Reputation: 70648

Use LEFT JOIN:

SELECT C.Cat, D.Drink
FROM CAT AS C
LEFT JOIN DRINK AS D
    ON C.CatId = D.CatId
    AND D.Drink = 'Milk'

Upvotes: 5

Related Questions