Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # foos TABLE
- #| id | name |
- #| 1 | No associated bars |
- #| 2 | bar WHERE col = 'x' |
- #| 3 | bar WHERE col = 'y' |
- # bars TABLE
- #| id | foo_id | col |
- #| 1 | 2 | 'x' |
- #| 2 | 3 | 'y' |
- # ALL results FROM the OUTER JOIN
- SELECT * FROM foos LEFT OUTER JOIN bars ON foos.id = bars.foo_id
- #| foos.id | foos.name | bars.id | bars.foo_id | col |
- #| 1 | No associated bars | NULL | NULL | NULL |
- #| 2 | bar WHERE col = 'x' | 1 | 2 | 'x' |
- #| 3 | bar WHERE col = 'y' | 2 | 3 | 'y' |
- # The query the OP AND myself would LIKE TO be executed
- SELECT * FROM foos LEFT OUTER JOIN bars ON foos.id = bars.foo_id AND bars.col = 'x'
- #| foos.id | foos.name | bars.id | bars.foo_id | col |
- #| 1 | No associated bars | NULL | NULL | NULL |
- #| 2 | bar WHERE col = 'x' | 1 | 2 | 'x' |
- #| 3 | bar WHERE col = 'y' | NULL | NULL | NULL |
- # Your (close but wrong) answer
- SELECT * FROM foos LEFT OUTER JOIN bars ON foos.id = bars.foo_id WHERE bars.col = 'x' OR bars.id IS NULL
- #| foos.id | foos.name | bars.id | bars.foo_id | col |
- #| 1 | No associated bars | NULL | NULL | NULL |
- #| 2 | bar WHERE col = 'x' | 1 | 2 | 'x' |
- #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