我有一个包含数据库的表,我希望在当前id之前获取两个数据,并在当前id之后获取两个数据。
primary_key id
1 345
2 356
3 400
4 102
5 210
6 190
案例:
我尝试这个SQL但不能正常工作,
$define_id = 400;
SELECT *
FROM table_name
WHERE (
id = IFNULL(
(
SELECT MIN(id)
FROM table_name
WHERE id > $define_id
), 0 )
OR id = IFNULL(
(
SELECT MAX(id)
FROM table_name
WHERE id < $define_id
), 0 )
)
LIMIT 2
在数据之前和之后获取的代码成功,但只有一个在之前和之后。我希望在之前和之后获得两个结果。
请帮忙。
答案 0 :(得分:1)
尝试使用您在问题中提到的输出。如果这不是你想要的,请更清楚地解释。
CREATE TABLE IF NOT EXISTS `docs` (
`primary_key` int(6) unsigned NOT NULL,
`id` int(3) unsigned NOT NULL,
PRIMARY KEY (`primary_key`,`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `docs` (`primary_key`, `id`) VALUES
('1', '345'),
('2', '356'),
('3', '400'),
('4', '102'),
('5', '210'),
('6', '190');
查询
(SELECT * FROM docs WHERE primary_key < (SELECT primary_key FROM docs WHERE id = 400) ORDER BY primary_key DESC LIMIT 2)
UNION ALL
(SELECT * FROM docs WHERE primary_key > (SELECT primary_key FROM docs WHERE id = 400) ORDER BY primary_key ASC LIMIT 2);
Sqlfiddle link http://sqlfiddle.com/#!9/e11c8d/2
答案 1 :(得分:0)
一种方法对两组使用union all
:
(select 'before' as which, t.*
from t cross join
(select primary_key from t where id = $define_id) x
where t.primary_key < x.primary_key
order by t.primary_key desc
limit 2
) union all
(select 'after' as which, t.*
from t cross join
(select primary_key from t where id = $define_id) x
where t.primary_key > x.primary_key
order by t.primary_key asc
limit 2
);