My tables:
test_people: test_things: test_people_things:
id|name id|name id|thing_id|people_id|rating
1|alice 1|hammer 1| 1 | 1 | 3
2|bob 2|table 2| 1 | 2 | 1
3|eve 3|chair 3| 2 | 1 | 0
4|glass 4| 3 | 2 | 2
What I want: Get all rows from test_things (but each row only once!) with the rating a given person applied to that thing or NULL, if no rating has been applied by that person so far. E.g. for people.id = 1 ("alice"), I'd expect this result:
thing.name|people.name|rating
hammer | alice | 3
table | alice | 0
chair | NULL | NULL
glass | NULL | NULL
This is my best try so far:
SELECT
test_things.name,
test_people.name,
test_people_things.rating
FROM
test_things LEFT JOIN test_people_things ON test_things.id = test_people_things.thing_id
LEFT JOIN test_people ON test_people_things.people_id = test_people.id
AND test_people.id = 1
The result is:
thing.name|people.name|rating
hammer | alice | 3
table | alice | 0
hammer | NULL | 1
chair | NULL | 2
glass | NULL | NULL
Here's the sqlfiddle with the test data.