开发者

Mysql Select Next & Prev row not order by id

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 ?


  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.


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];

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜