任何人都知道如何将这些结合到一个声明中?这是我所追求的特定区块的所有会话的lesson_id(...)
$query = "
SELECT session_id FROM cdu_blocks_sessions
JOIN cdu_sessions ON cdu_sessions.id = cdu_blocks_sessions.session_id
WHERE block_id = $block_id
AND enabled = 1";
$session_ids = cdu_get_query_results($db, $query, __LINE__);
$lesson_ids = array();
foreach ($session_ids as $session_id) {
$query = "
SELECT lesson_id FROM cdu_sessions_lessons
JOIN cdu_lessons ON cdu_lessons.id = cdu_sessions_lessons.lesson_id
WHERE session_id = " . $session_id['session_id'] . "
AND enabled = 1";
$lesson_ids = array_merge($lesson_ids, cdu_get_query_results($db, $query, __LINE__));
}
cdu_sessions:
------------------------------
|id |name |enabled |
------------------------------
|1 |session 1 |1 |
|2 |session 2 |1 |
|3 |session 3 |1 |
|4 |session 4 |0 |
|5 |session 5 |1 |
|6 |session 6 |0 |
|7 |session 7 |1 |
|8 |session 8 |1 |
------------------------------
cdu_blocks_sessions:
---------------------------
|id |block_id |session_id |
---------------------------
|1 |1 |1 |
|1 |1 |2 |
|1 |1 |3 |
|1 |2 |4 |
|1 |2 |5 |
|1 |2 |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 |
-----------------------------
cdu_sessions_lessons:
----------------------------
|id |session_id |lesson_id |
----------------------------
|1 |1 |1 |
|1 |1 |2 |
|1 |1 |3 |
|1 |2 |4 |
|1 |2 |5 |
----------------------------
答案 0 :(得分:0)
尝试 SQL Server
的此查询SELECT *
FROM (
SELECT session_id FROM cdu_blocks_sessions
JOIN cdu_sessions ON cdu_sessions.id = cdu_blocks_sessions.session_id
WHERE block_id = $block_id
AND enabled = 1
) S
CROSS APPLY (
SELECT lesson_id FROM cdu_sessions_lessons
JOIN cdu_lessons ON cdu_lessons.id = cdu_sessions_lessons.lesson_id
WHERE session_id = S.session_id
AND enabled = 1
) L
有关交叉申请的更多信息
SQL Server CROSS APPLY and OUTER APPLY
另一种方式
SELECT L.*
FROM (
SELECT session_id FROM cdu_blocks_sessions
JOIN cdu_sessions ON cdu_sessions.id = cdu_blocks_sessions.session_id
WHERE block_id = $block_id
AND enabled = 1
) 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
) L S.session_id = L.session_id