sql - 如何从 3 个表中选择特定数据? [PostgreSQL 9.1]

标签 sql postgresql select join 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)

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

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

最佳答案

试试这个

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

关于sql - 如何从 3 个表中选择特定数据? [PostgreSQL 9.1],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14423556/

相关文章:

Mysql表之间相互链接

php - 使用 mysql 建立 php 错误数据库的最佳方法?

postgresql - plpgsql中的动态变量名(字符串到变量名)

sql - SQL 中的 SELECT 语句用于过滤掉多个条目

sql - 加入一列,如果没有匹配加入另一列

postgresql - 传递一个函数名作为参数

python - Psycopg2 - 属性错误 : 'NoneType' object has no attribute 'fetchall'

c - 实现 select() + 线程池的正确方法是什么?

mysql - 具体的mysql选择查询

Mysql无法选中表中的记录