SELECT 需要与 PostgreSQL 中的一对多表进行多次连接

SELECT requiring multiple joins with one to many tables in PostgreSQL

玩具示例:我有一个数据库模式显示在这个 EDR 图中:

我想得到全部所有的书[=30] =]学习小组一个单身 学生.

+------------+---------+----------------+
| student.id | book.id | study_group.id |
+------------+---------+----------------+
|          1 |       1 |              1 |
|          1 |       2 |              1 |
|          1 |       3 |              1 |
|          1 |       4 |              2 |
|          1 |       1 |              2 |
+------------+---------+----------------+

我不确定在这种情况下如何构造多重连接,

SELECT student.id, book.id, study_group.id
FROM ...
    INNER JOIN...
    INNER JOIN...
WHERE student.id == 1

这是一种使用聚合的方法:

select b.id, b.title
from books b
inner join borrowed bd on bd.book_id = b.id
inner join studyGroup sg on sg.id = bd.study_group_id
where sg.student_id = 1
group by b.id, b.title
having count(*) = (select count(*) from studyGroup sg1 where sg1.student_id = 1)

我推荐你阅读SQL JOIN and different types of JOINs

如果您想要 table 如图所示:

SELECT student.id, book.id, study_group.id
FROM student
    INNER JOIN study_group on (student.id = study_group.student_id)
    INNER JOIN borrowed on (study_group.id = borrowed.group_id)
    INNER JOIN book on (borrowed.book_id = book.id)
WHERE student.id == 1