Mysql 选择下一步 &上一行不按 ID 排序

发布于 2024-10-08 03:00:08 字数 258 浏览 0 评论 0原文

我有一个按 NAME 排序的查询,它返回 smt,如下所示:

 ID     NAME
2121927 AAA
2123589 AAB
2121050 AAC
2463926 BBB ---> known ID
2120595 CCC
2122831 DDD
2493055 EEE
2123583 EEF

我需要知道已知 ID 的下一个 ID 和上一个 ID(如果存在)&&姓名 怎么可能只有 1 个查询呢?

I have a query ordered by NAME that return smt like this:

 ID     NAME
2121927 AAA
2123589 AAB
2121050 AAC
2463926 BBB ---> known ID
2120595 CCC
2122831 DDD
2493055 EEE
2123583 EEF

I need to know the next ID and the prev ID (if exists) of known ID && NAME
How is it possible with only 1 query ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

  SELECT *,
         'next'
    FROM table
   WHERE `name` > 'BBB'
ORDER BY `name`
   LIMIT 1

UNION

  SELECT *,
         'previous'
    FROM table
   WHERE `name` < 'BBB'
ORDER BY `name` DESC
   LIMIT 1

如果您不知道特定的 BBB name 字段值 - 您可以将其替换为子查询,例如 SELECT name FROM table WHERE id = 42,其中42 是已知的ID 值。

  SELECT *,
         'next'
    FROM table
   WHERE `name` > 'BBB'
ORDER BY `name`
   LIMIT 1

UNION

  SELECT *,
         'previous'
    FROM table
   WHERE `name` < 'BBB'
ORDER BY `name` DESC
   LIMIT 1

If you don't know particular BBB name field value - you could replace it with subquery like SELECT name FROM table WHERE id = 42, where 42 is the known ID value.

巡山小妖精 2024-10-15 03:00:08

我是这样做的:
它不是最快的,但它不关心字段的顺序。
按照您想要的顺序查询数据库中的所有行。
使用 php foreach 查找当前 id。
获取当前id的数组索引,使索引+1或索引-1。

$current_id = 6;
$data = get_all_data_from_db();
foreach($data as $index=>$row) {
if($current_id == $row['id']) {
$next = $index+1;
$prev = $index-1;
<代码>}
$previous_row = $data[$prev];
$next_row = $data[$next];

I did it like this:
Its not the fastest, but it dont cares about order of fields.
Query all rows from db in order that you want.
Use php foreach to find current id.
Get array index of current id, make index +1 or index -1.

$current_id = 6;
$data = get_all_data_from_db();
foreach($data as $index=>$row) {
if($current_id == $row['id']) {
$next = $index+1;
$prev = $index-1;
}
$previous_row = $data[$prev];
$next_row = $data[$next];

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