dongsi3826 2013-09-02 09:29
浏览 75
已采纳

更新列的最大值在mysql中不起作用

I have tried to set the max value for the particular column but that is not working for me. I do not know where i'm going wrong.

UPDATE `upload_video` 
             SET order_id ='select max(order_id)+1 
             FROM upload_video' 
             WHERE `video_id` = 22

This is my query i run the select max(order_id)+1 from upload_video query separately which is giving the result. But if i use this query in update query, the query is executing without error. But the order_id is not updating properly. please help me

  • 写回答

3条回答 默认 最新

  • dongle7553 2013-09-02 09:43
    关注

    Your query is almost correct in standard SQL, you only need to use brackets () instead of apostrophe ':

    SET order_id = (SELECT MAX(...) ...)
    

    but MySQL doesn't allow you to update a table while selecting from the same table, a workaround is to use a subquery that calculates the value that you need, and to join your subquery with the table you need to update:

    UPDATE
      upload_video JOIN (SELECT COALESCE(MAX(order_id),0)+1 max_id
                         FROM upload_video) s
    SET
      upload_video.order_id=s.max_id
    WHERE
      video_id=22
    

    Please see fiddle here.

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

报告相同问题?

悬赏问题

  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据