3

Not great with SQL queries, need a little help to get a working query with two inner joins.

Here's my tables:

posts users orgs

posts/users share a key of "user_id" which allows me to pull the posts table and have it also include the username of the user from the users table. I need to pull more data though.. I need to also include the "org_id" from the users table and then pull in the corresponding row from the orgs table.

Currently my SQL query is

SELECT p.*, u.username FROM posts p
INNER JOIN users u
ON p.user_id = u.user_id
ORDER BY p.post_id DESC;

and this correctly gets me the full list of posts stored in the posts table and includes the username.

I need it to include data from the orgs table.

So if Post #1 is created by user #2, I get that info together. How can I have it do another inner join that takes user #2 and gets the full set of data from the user's corresponding org?

3 Answers 3

4

If I got it correctly, the query would be the following:

SELECT p.*, u.username,o.* FROM posts p
INNER JOIN users u
ON p.user_id = u.user_id
INNER JOIN orgs o
ON u.org_id=o.org_id
ORDER BY p.post_id DESC;

You can learn more about joins here.

Sign up to request clarification or add additional context in comments.

Comments

0

You can join any number of tables as you want in the same way. Please try now :

SELECT p.*,o.*, u.username FROM posts p
INNER JOIN users u
    ON p.user_id = u.user_id
INNER JOIN ORGS O 
    ON u.org_id = o.org_id 
ORDER BY p.post_id DESC;

More examples can be found here.

1 Comment

Thaaaaank you! This is perfect.
0

You’re almost there. Just add the orgs table in another join condition:

SELECT p.*, o.*, u.username FROM posts p
INNER JOIN users u
ON p.user_id = u.user_id
INNER JOIN orgs o
ON o.org_id = u.org_id
ORDER BY p.post_id DESC;

1 Comment

Thank you! This is what I needed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.