Here is my ER diagram. If I know the user_id, how can I get a single user's user data=>projects=>boards=>posts using a single SQL query?
I have found out about recursive CTE, but all of the examples I can find have all of the data stored into a single table. I have my data split into 4 tables. Is there a way to get all user data here?
I don't have any SQL to show I tried, because honestly I don't even know where to begin. I thought of just adding a user_id field to every table, but it doesn't seem like the correct solution.
EDIT: Is this a good way to deal with the redundant data from the joins?
I have 3 ideas:
1-> Get all of the data with duplicates. No duplicate data in database and one query, but sending more data than I need to.
2-> Split the query into four separate queries for each table. No duplicate data, but then I am running four separate queries.
3-> Add 'user_id' to every table, and query each table directly. Then I have redundant data in my database.
4-> ?? A better option? Or more concise query?
Here is my idea to split the queries (2)
-- user data
SELECT nickname, theme FROM users WHERE user_id = 'exampleid';
-- project data
SELECT
pr.project_id,
pr.time_created ,
pr.time_last_modified,
pr.title
FROM users u
INNER JOIN projects pr
ON u.user_id = pr.fk_projects_users
WHERE u.user_id = 'exampleid';
-- board data
SELECT
b.board_id,
b.fk_boards_projects,
b.title,
b.order_position,
b.color
FROM users u
INNER JOIN projects pr
ON u.user_id = pr.fk_projects_users
INNER JOIN boards b
ON pr.project_id = b.fk_boards_projects
WHERE u.user_id = 'exampleid';
-- post data
SELECT
po.post_id,
po.fk_posts_boards,
po.time_created,
po.title,
po.priority,
po.time_due,
po.body
FROM users u
INNER JOIN projects pr
ON u.user_id = pr.fk_projects_users
INNER JOIN boards b
ON pr.project_id = b.fk_boards_projects
INNER JOIN posts po
ON po.post_id = b.board_id
WHERE u.user_id = 'exampleid'

users u Inner Join projects pyou ask for ALL users and ALL projects, whether the user worked on it or not. By addingOn u.user_id=pr.fk_projects_usersyou throw out all the users that did not work on a project and keep only the list of users and projects they worked on.