duanhui9840 2012-04-30 07:20
浏览 120
已采纳

基于int的自定义字段排序

If I have a list of database fields:

id    order    title
1     3        This is a post
2     1        This is another post
3     2        This is also a post
4     4        This is still a post

And I want change the order of these based on order.
If I set order on id #1 to 2 I want order on id #3 to be set to 3.
If I set order on id #4 to 1 I want order on id #1 to be 4, order on id #2 to be 2, order on id #3 to be 3 etc. etc.

How can I do this? I think it should be quite simple but I can't figure it out.
I have searched but I don't know what to search for...

  • 写回答

3条回答

  • duan7007 2012-04-30 07:46
    关注

    You can do it in SQL with two UPDATE statements:

    START TRANSACTION;
    SELECT order FROM t WHERE order BETWEEN $new_order AND $old_order FOR UPDATE;
    
    UPDATE t SET order = order + 1  WHERE order BETWEEN $new_order AND $old_order;
    UPDATE t SET order = $new_order WHERE id = $id;
    
    COMMIT;
    

    I have locked the table during these updates to prevent concurrency issues (however, note that transactions/locks are only applicable to InnoDB tables).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?