Advertisement
Guest User

Untitled

a guest
Jul 10th, 2013
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # foos TABLE
  2. #| id | name                |
  3. #| 1  | No associated bars  |
  4. #| 2  | bar WHERE col = 'x' |
  5. #| 3  | bar WHERE col = 'y' |
  6.  
  7. # bars TABLE
  8. #| id | foo_id | col |
  9. #| 1  | 2      | 'x' |
  10. #| 2  | 3      | 'y' |
  11.  
  12. # ALL results FROM the OUTER JOIN
  13. SELECT * FROM foos LEFT OUTER JOIN bars ON foos.id = bars.foo_id
  14. #| foos.id | foos.name           | bars.id | bars.foo_id | col  |
  15. #| 1       | No associated bars  | NULL    | NULL        | NULL |
  16. #| 2       | bar WHERE col = 'x' | 1       | 2           | 'x'  |
  17. #| 3       | bar WHERE col = 'y' | 2       | 3           | 'y'  |
  18.  
  19. # The query the OP AND myself would LIKE TO be executed
  20. SELECT * FROM foos LEFT OUTER JOIN bars ON foos.id = bars.foo_id AND bars.col = 'x'
  21. #| foos.id | foos.name           | bars.id | bars.foo_id | col  |
  22. #| 1       | No associated bars  | NULL    | NULL        | NULL |
  23. #| 2       | bar WHERE col = 'x' | 1       | 2           | 'x'  |
  24. #| 3       | bar WHERE col = 'y' | NULL    | NULL        | NULL |
  25.  
  26. # Your (close but wrong) answer
  27. SELECT * FROM foos LEFT OUTER JOIN bars ON foos.id = bars.foo_id WHERE bars.col = 'x'  OR bars.id IS NULL
  28. #| foos.id | foos.name           | bars.id | bars.foo_id | col  |
  29. #| 1       | No associated bars  | NULL    | NULL        | NULL |
  30. #| 2       | bar WHERE col = 'x' | 1       | 2           | 'x'  |
  31.  
  32. #The 3rd ROW would have bars.col = 'y' AND bars.id = 2, so it won't return the row. We need the row to return the foo.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement