我有一个课程表和课程表,如下所示
course_id lesson_id content_id seq_no
1 1 1 1
1 1 2 2
1 5 3 1
1 5 4 2
1 8 12 1
leson_id lesson_no course_id
1 1 1
5 3 1
8 2 1
我想在我的应用程序中具有上一个下一个按钮。如果当前课程中有下一课,则单击“ next”;如果当前课程有下一课,则查询应提供下一课目ID;如果没有下一课,则应跳至下一课和第一课。内容的序号为seq_no,课程为lesson_no
我在下面进行了查询,但是我无法跳到下一课
下一次点击:
SELECT *
FROM course_content
WHERE course_id =1
AND content_id = (
SELECT MIN( content_id )
FROM course_content
WHERE lesson_id =1
AND content_id >21
ORDER BY seq_no ASC )
以前的点击
SELECT *
FROM course_content
WHERE course_id =1
AND content_id = (
SELECT MAX( content_id )
FROM course_content
WHERE lesson_id =1
AND content_id <2
ORDER BY seq_no DESC )
答案 0 :(得分:0)
我会这样:
SELECT c.course_id
, c.lesson_id
, c.content_id
, c.seq_no
, l.lesson_no
FROM course_content c
JOIN lesson l
ON l.lesson_id = c.lesson_id
WHERE c.course_id = 1
AND l.lesson_no >= :curr_lesson_no
AND ( c.seq_no > :curr_seq_no
OR
l.lesson_no > :curr_lesson_no2
)
ORDER
BY l.lesson_no
, c.seq_no
LIMIT 1
只需在查询参数中提供当前行的值lesson_no
和seq_no
如果我们无法保留当前行的lesson_no
和seq_no
,而我们只有content_id
,那么我们可以运行查询以获取这些
SELECT cl.lesson_no AS curr_lesson_no
, cc.seq_no AS curr_seq_no
FROM course_content cc
JOIN lesson cl
ON cl.lesson_id = cc.lesson_id
WHERE cc.content_id = :curr_content_id
ORDER
BY cl.lesson_no
, cc.seq_no
LIMIT 1
我们可以将这两个查询放在一起……
SELECT c.course_id
, c.lesson_id
, c.content_id
, c.seq_no
, l.lesson_no
FROM ( SELECT cl.lesson_no AS curr_lesson_no
, cc.seq_no AS curr_seq_no
FROM course_content cc
JOIN lesson cl
ON cl.lesson_id = cc.lesson_id
WHERE cc.content_id = :curr_content_id
ORDER
BY cl.lesson_no
, cc.seq_no
LIMIT 1
) q
JOIN lesson l
ON l.lesson_no >= q.curr_lesson_no
JOIN course_content c
ON c.lesson_id = l.lesson_id
WHERE c.course_id = 1
AND ( c.seq_no > q.curr_seq_no
OR
l.lesson_no > q.curr_lesson_no
)
ORDER
BY l.lesson_no
, c.seq_no
LIMIT 1