如何在 MySQL 中使用单个查询查找上一条和下一条记录?
我有一个数据库,我想使用单个查询找出按 ID 排序的上一条和下一条记录。 我尝试建立一个工会,但没有成功。 :(
SELECT * FROM table WHERE `id` > 1556 LIMIT 1
UNION
SELECT * FROM table WHERE `id` <1556 ORDER BY `product_id` LIMIT 1
有任何想法吗? 多谢。
I have a database, and I want to find out the previous and next record ordered by ID, using a single query. I tried to do a union but that does not work. :(
SELECT * FROM table WHERE `id` > 1556 LIMIT 1
UNION
SELECT * FROM table WHERE `id` <1556 ORDER BY `product_id` LIMIT 1
Any ideas?
Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要更改
ORDER BY
:这可确保
id
字段在获取顶部结果之前顺序正确。您还可以使用 MIN 和 MAX:
不过,应该注意的是,不建议在生产代码中使用
SELECT *
,因此请在SELECT
语句中命名您的列。You need to change up your
ORDER BY
:This ensures that the
id
field is in the correct order before taking the top result.You can also use MIN and MAX:
It should be noted that
SELECT *
is not recommended to have in production code, though, so name your columns in yourSELECT
statement.