如何在 MySQL 中使用单个查询查找上一条和下一条记录?

发布于 2024-07-25 17:47:30 字数 242 浏览 8 评论 0原文

我有一个数据库,我想使用单个查询找出按 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

往事随风而去 2024-08-01 17:47:30

您需要更改 ORDER BY

SELECT * FROM table WHERE `id` > 1556 ORDER BY `id` ASC LIMIT 1
UNION 
SELECT * FROM table WHERE `id` < 1556 ORDER BY `id` DESC LIMIT 1

这可确保 id 字段在获取顶部结果之前顺序正确。

您还可以使用 MIN 和 MAX:

SELECT
    * 
FROM
    table 
WHERE 
    id = (SELECT MIN(id) FROM table where id > 1556) 
    OR id = (SELECT MAX(id) FROM table where id < 1556)

不过,应该注意的是,不建议在生产代码中使用 SELECT *,因此请在 SELECT 语句中命名您的列。

You need to change up your ORDER BY:

SELECT * FROM table WHERE `id` > 1556 ORDER BY `id` ASC LIMIT 1
UNION 
SELECT * FROM table WHERE `id` < 1556 ORDER BY `id` DESC LIMIT 1

This ensures that the id field is in the correct order before taking the top result.

You can also use MIN and MAX:

SELECT
    * 
FROM
    table 
WHERE 
    id = (SELECT MIN(id) FROM table where id > 1556) 
    OR id = (SELECT MAX(id) FROM table where id < 1556)

It should be noted that SELECT * is not recommended to have in production code, though, so name your columns in your SELECT statement.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文