How to select specific data from 3 tables? [PostgreSQL 9.1]
# select * from users ;
user_id | login | email | password | firstname | lastname
---------+--------+-------------------------+----------+-----------+----------
1 | katie | katie.s@ymail.com | secret | Katie | Secret
(1 row)
# select * from forum;
forum_id | forum_name | group_id | forum_parent
----------+------------+----------+--------------
1| 1st forum | 1 | -1
(1 row)
# select * from groups;
group_id | group_name | group_description | group_founder
----------+-----------------------+-------------------------------------------------+---------------
1 | Java programming | System.out.println("Hello world in Java!"); :) | 1
(1 row)
I have these 3 tables in my database. I would like to get forums from it that are created by the user using id = 1
. How to do it? (in the table groups
, the id
user who created such a group is called group_founder
).
I mean, with the output above, you can see that user with id = 1
created a Java Programming group and then created a forum in that group called "1st Forum". Please, help:)
+3
Katie
source
to share
2 answers
try it
SELECT *
FROM forum f
JOIN groups g ON g.group_id = f.group_id
JOIN users u ON u.user_id = g.group_founder
WHERE u.user_id = 1
+3
DON
source
to share
According to your inputs, the query could be like this
SELECT U.login,U.email,U.firstname
FROM users U JOIN groups G ON U.user_id = G.group_founder
JOIN forum F ON G.group_id = F.group_id
WHERE U.user_id = 1
DEMO
+3
MuhammadHani
source
to share