0

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.

9
  • 2
    LEFT JOIN is your friend. Commented Feb 4, 2014 at 15:56
  • Sounds like maybe you are looking for an Outer join: w3schools.com/sql/sql_join_left.asp Commented Feb 4, 2014 at 15:56
  • 4
    @Andrew Those pages (W3schools) have so many errors that I think that links to them should be removed as spam - from a professional site as SO. Commented Feb 4, 2014 at 16:00
  • @ypercube, I still think the links are useful. W3 links are way easier to understand for beginners than MS's syntax pages. Commented Feb 4, 2014 at 16:06
  • @Sev09 I'd rather they spend extra time to learn the correct way, then spend less time to learn the wrong way. Commented Feb 4, 2014 at 16:07

1 Answer 1

5

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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.