Select 指定行周围的行,结合 WHERE 和 ORDER BY

Select rows around a specified row, combined with WHERE and ORDER BY

我有一个包含 3 个字段的 table:idpublicdate

如何进行 MySQL 查询,使行按 date 排序,具有 public = false 的行被省略,并且只有前 5 行和后 5 行id = x 的行被提取了吗? (id = x那一行当然也可以取。)

假设 "before" 和 "after" 指的是日期,那么你可以使用 union all:

(select t.*
 from table t
 where t.public = false and
       t.date <= (select t2.date from table t2 where t2.id = x)
 order by date desc
 limit 6
)
union all
(select t.*
 from table t
 where t.public = false and
       t.date > (select t2.date from table t2 where t2.id = x)
 order by date asc
 limit 5
)

第一个子查询获取 6 行,其日期是 "x" 日期或之前的日期。第二个严格地得到 5 行。