我在Python中使用sqlite3。我想在列出教室时选择距当前时间最近的时间。这是[时间表]数据库。
[ timetable ]
lecture_room start_time
---------------------
A211 13:00
A211 14:00
B107 13:00
如果我查询当前时间是11:34,预期结果如下。 (我希望一个教室只能被查询一次。)
lecture_room next_time
---------------------
A211 13:00
B107 13:00
如果我查询当前时间是13:34,预期结果如下。
lecture_room next_time
---------------------
A211 14:00
B107 <null>
这是我编写的SQL查询,但此SQL查询会产生错误([1] [SQLITE_ERROR] SQL error or missing database (no such column: L)
)
SELECT lecture_room as L,
(SELECT MIN(start_time)
FROM timetable
WHERE
time("now", "localtime") <= time(start_time)
AND
L = lecture_room
)
FROM timetable;
答案 0 :(得分:1)
要为每个房间只输入一个条目,请使用DISTINCT(在子查询中,否则它将适用于两个列)。
correlated subquery几乎是正确的;你必须参考正确的表格:
SELECT lecture_room,
(SELECT min(start_time)
FROM timetable AS t2
WHERE t2.lecture_room = t1.lecture_room
AND t2.start_time >= time('now', 'localtime')
) AS next_time
FROM (SELECT DISTINCT lecture_room
FROM timetable) AS t1;