我有一张名为books的表,其中包含以下数据:
id | description | section
1 | textbook 1 | 1
2 | textbook 2 | 1
3 | textbook 3 | 1
我使用以下查询来选择id 2以及第1部分中的下一行和前一行:
SELECT id FROM books where id IN
(2,
(SELECT id FROM books WHERE id < 2 LIMIT 1),
(SELECT id FROM books WHERE id > 2 LIMIT 1)
)
AND section = 1
当我添加section = 1
时,查询只返回id 2,而它应返回所有3个ID,但是当我删除此部分时,它会选择所有3个ID。我的方案实际上比这更复杂,但我简化它来解释情况。那么,我上面做错了什么?
答案 0 :(得分:2)
(SELECT id
FROM books
WHERE id < 2 and section = 1
ORDER BY id DESC
LIMIT 1)
UNION
(SELECT id
FROM books
WHERE id >= 2 and section = 1
ORDER BY id ASC
LIMIT 2)
您的查询存在的问题是,您选择的随机ID小于2且大于2,而不考虑该部分。如果这些ID不在第1部分中,则它们不会包含在结果中。
外部查询中的WHERE子句未分发到子查询中。子查询是独立执行的,返回ID,这些ID被放入IN
子句中。然后外部查询按部分过滤。
答案 1 :(得分:0)
SELECT id FROM books where id IN
(2,
(SELECT id FROM books WHERE id < 2 ORDER BY id DESC LIMIT 1),
(SELECT id FROM books WHERE id > 2 ORDER BY id ASC LIMIT 1)
)
AND section = 1
ORDER BY
应该可以解决问题。
答案 2 :(得分:0)
我很确定这可以解决您的问题:
SELECT id
FROM books
WHERE id IN
(2
, ((SELECT id FROM books WHERE id < 2 AND section = 1 ORDER BY id DESC LIMIT 1))
, ((SELECT id FROM books WHERE id > 2 AND section = 1 ORDER BY id ASC LIMIT 1))
)
AND section = 1