SQL:三重嵌套多对多查询

时间:2014-02-06 19:20:52

标签: sql

我正在尝试修复我的嵌套查询,我有这些表:

cdu_groups_blocks
------------------------
|id |group_id |block_id|
------------------------
|1  |1        |1       |
|2  |1        |2       |
|3  |1        |3       |
------------------------

cdu_blocks:                        cdu_blocks_sessions:
--------------------------         ---------------------------
|id |name       |enabled |         |id |block_id |session_id |
--------------------------         ---------------------------
|1  |block_1    |1       |         |1  |1        |1          |
|2  |block_2    |1       |         |2  |1        |2          |
|3  |block_3    |1       |         |3  |2        |3          |
--------------------------         |4  |2        |4          |
                                   |5  |3        |5          |
                                   |6  |3        |6          |
                                   ---------------------------

cdu_sessions:                      cdu_sessions_lessons
--------------------------         ----------------------------
|id |name       |enabled |         |id |session_id |lesson_id |
--------------------------         ----------------------------
|1  |session_1  |1       |         |1  |1          |1         |
|2  |session_2  |1       |         |2  |1          |2         |
|3  |session_3  |1       |         |3  |2          |3         |
|4  |session_4  |0       |         |4  |4          |4         |
|5  |session_5  |1       |         |5  |4          |5         |
|6  |session_6  |0       |         |6  |5          |6         |
--------------------------         ----------------------------

cdu_lessons:
--------------------------
|id |name       |enabled |
--------------------------
|1  |lesson_1   |1       |
|2  |lesson_2   |1       |
|3  |lesson_3   |1       |
|4  |lesson_4   |1       |
|5  |lesson_5   |0       |
|6  |lesson_6   |0       |
--------------------------

这是一个多对多链接到另一个多对多链接到另一个多对多链接。

基本上我想获得与特定group_id相关的所有lesson_id。

到目前为止,我已经有了这个,但它会引发各种SQL错误:

SELECT b.* FROM
(
    SELECT block_id, group_id FROM cdu_groups_blocks
    JOIN cdu_blocks ON cdu_blocks.id = cdu_groups_blocks.block_id
    WHERE group_id = $group_id
    AND enabled = 1
) AS b 
INNER JOIN 
(
    SELECT l.* FROM 
    (
        SELECT session_id, block_id FROM cdu_blocks_sessions
        JOIN cdu_sessions ON cdu_sessions.id = cdu_blocks_sessions.session_id
        AND enabled = 1
) AS s
INNER JOIN 
(
    SELECT lesson_id, session_id FROM cdu_sessions_lessons
    JOIN cdu_lessons ON cdu_lessons.id = cdu_sessions_lessons.lesson_id
    WHERE enabled = 1
) AS l 
WHERE s.session_id = l.session_id
) AS sl
WHERE sl.block_id = g.block_id

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

sl.block_id 来自您在 sl 子选择内的第一个选择中的 s 表格。

得到它。变化:

SELECT l.* FROM ...

SELECT l.*, s.block_id FROM ...