简体   繁体   中英

How to upgrade next/previous record in mysql

mysql fetch previous or next record order by anyother field name and not by using order by id

select * from table where id > $id order by name asc limit 1
select * from table where id < $id order by name desc limit 1

I am able to get next and previous records but in this case how can i upgrade next and previous records.

ID Links          orderID
14 Google.com     1
15 Yahoo.com      2
20 gmail.com      3
25 facebook.com   4

What about if i use + and - button in front each link to upgrade and downgrade them and then rearrange the menus order by orderID ?

Well, if you really want to do it in a single query, you can use a subquery to find out the ID you need to update. The problem lies in the fact that MySQL cannot update the same table that you're trying to subquery, for obvious data integrity reasons. So you'll need to use some workarounds for that, such as creating a temporary table in a subquery.

UPDATE table AS t
SET [...]
WHERE t.`id` = (select * FROM (select `id` from table where `id` > $id order by `id` asc limit 1) AS sq)

There is absolutely no need to do the two selects. You can do the following:

UPDATE table SET field='some value' WHERE id=$id+1

UPDATE table SET field='some value' WHERE id=$id-1

There you go :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM