doudong3570 2012-04-28 22:49
浏览 145
已采纳

使用“排序”列在MySQL表中排列行

I arrange photos on an album by using a column "sort" in the table. This means that an album will be displayed with "ORDER BY sort".

I have a feature that allows users to arrange the photos on an album, by dragging and dropping photos, in javascript, and then pressing the "Save" button.

An array (with the sorted Photo IDs) is sent to the process (in PHP), and then I want to re-sort the rows on the table.

The easiest way in my mind to do is:

for ($c=0; $c<$length; $c++) {
    mysql_query('UPDATE photos SET sort="'.$c.'" WHERE id="'.$array[$c].'"');
}

(please ignore sanitization, duplicates and other verifications here)

But I'm worried about the amount of queries that are made in a cycle like this.

How would you improve this approach?

Thank you.

  • 写回答

3条回答 默认 最新

  • douping1993 2012-04-28 23:15
    关注

    First of all, I don't think there's anything wrong with issuing multiple queries. Did you test it? Are you sure it would be a performance bottleneck? I don't think so.

    But anyway, solution #1 is to use REPLACE in conjunction with the VALUES clause. In that case, though, you need to explicitly specify data for all columns of the table, otherwise the data in those columns will be erased (set to default value).

    Solution #2 is just for fun. I don't think anyone would use it, but still:

    UPDATE photos
    SET sort = (
      SELECT sort FROM (
        SELECT 1 id, 1 sort UNION
        SELECT 2 id, 2 sort UNION
        SELECT 123 id, 3 sort) t
      WHERE t.id = photos.id)
    WHERE id IN (1, 2, 123)
    

    Solution #3 is virtually the same as Zombaya's:

    UPDATE photos
    SET sort =
      IF(id = 1, 1,
      IF(id = 2, 2,
      IF(id = 123, 3,
        0)))
    WHERE id IN (1, 2, 123)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?