I’m trying to get a MySQL query to give me related data 2 tables away. So one user would have access to 2 projects, with a total of 3 posts (in “stream”). Essentially, I want to get the associated projects in project_users and then get posts in stream associated those projects.
The data looks something like this:
Table 1: user (1 user identified by ‘id’)
Table 2: project_users (user associated with 2 projects in this case)
Table 3: stream (posts attached to different projects, but I should get 3 based on my test data set)
My (broken) query looks like this:
SELECT U.`id`, P.`kf_users`, P.`kf_projects`, S.`kf_projects`, S.`body`
FROM users U
LEFT JOIN projects_users P ON U.`id` = P.`kf_users`
LEFT JOIN stream S ON P.`kf_users` = S.`kf_projects`
WHERE U.`id` = 1
What on earth am I missing? I tried subqueries, but it wouldn’t let me have multiple rows in it, rendering it useless in the form I had it.
Thanks!
Really?! Then try changing it to this:
I suspect that will give you no results too. Knowing that this query also fails should hopefully help you to find the problem more quickly (you don’t have a user with id 1).
Note: If this gives you a result, then the query you posted above with the LEFT JOIN should return some rows too, because adding a LEFT JOIN shouldn’t remove any rows.
Update: Try adding aliases to make the column names unique: