Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL query with two inner joins

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?

like image 672
KleinBottleCode Avatar asked Apr 24 '26 15:04

KleinBottleCode


1 Answers

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.

like image 69
Neto Costa Avatar answered Apr 26 '26 05:04

Neto Costa