假设您有一个表,其中包含一个名为'table_id‘的整数主键
是否可以在单个查询中提取具有特定id的行以及它前面的X行和它后面的X行?
例如,如果您的id是(1,2, 8,12, 16,120,250 ,354),X是2,您拥有的id是16,那么select应该返回id为8,12,16,120,250的行
我知道如何在几个查询中做到这一点,我想知道如何在一次遍历中做到这一点(子查询、联合查询和所有查询都很好)。
谢谢你的帮助
发布于 2009-12-11 04:00:18
您可以在之前的项目和之后的项目之间进行联合,但必须对它们进行子查询才能对其进行排序:
select * from (
select * from thetable where table_id >= 16 order by table_id limit 3
) x
union all
select * from (
select * from thetable where table_id < 16 order by table_id desc limit 2
) y
order by table_id发布于 2009-12-11 03:56:18
试试这个:
select table_id from table where id > 16 order by table_id desc limit 2
union all
select table_id from table where id <= 16 order by table_id asc limit 3;发布于 2009-12-11 03:58:59
使用MySQL的LIMIT语法和UNION:
SELECT table_id FROM table WHERE id > 16 ORDER BY table_id ASC LIMIT 2
UNION
SELECT table_id FROM table WHERE id <= 16 ORDER BY table_id DESC LIMIT 3https://stackoverflow.com/questions/1883507
复制相似问题