Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select specific data from 3 tables? [PostgreSQL 9.1]

# select * from users ;
 user_id | login  |          email          | password | firstname | lastname 
---------+--------+-------------------------+----------+-----------+----------
       1 | katie  | [email protected]       | 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 those 3 tables in my database. I would like to get from it forums which are created by user with id = 1. How to do this? (in table groups, id of the user which created such group is called group_founder).

I mean, with the output above, you can see that user with id = 1 created a group "Java programming" and then created within this group a forum, called "1st forum". Please, help :)

like image 420
Katie Avatar asked Apr 25 '26 15:04

Katie


2 Answers

Try this

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
like image 143
Hary Avatar answered Apr 28 '26 07:04

Hary


As per your inputs, the query may be that way

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

like image 45
Muhammad Hani Avatar answered Apr 28 '26 07:04

Muhammad Hani