3
# 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)

我的数据库中有这 3 个表。我想从中获得由用户创建的论坛id = 1。这该怎么做?(在表中groupsid创建此类组的用户被称为group_founder)。

我的意思是,通过上面的输出,您可以看到该用户id = 1创建了一个“Java 编程”组,然后在该组中创建了一个论坛,称为“第一个论坛”。请帮忙 :)

4

2 回答 2

3

试试这个

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
于 2013-01-20T10:27:06.403 回答
3

根据您的输入,查询可能是这样的

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

演示

于 2013-01-20T10:29:49.063 回答