doufu9947 2013-12-26 17:45
浏览 197
已采纳

MySQL中用于根据另一个字段的最大值更新字段的嵌套select语句会产生错误

I want to execute the following SQL statement in PhP. I have simplified it below. I would like to know the MySQL modifications to make it work. I tried a few like giving aliases to the tables but it did not work:

     update T1 set col1 = 500 
         where  col2 = 12345 and 
                col3 = (select max(col3) from T1 where  col2 = 12345) 

I want to update a record which has the max value for one column. There is only one table involved in the entire query. I am using PDO, if that is relevant.

The error given is:

#1093 - You can't specify target table 'T1' for update in FROM clause 
  • 写回答

1条回答 默认 最新

  • dongzha5934 2013-12-26 17:49
    关注

    Use a join instead:

     update T1 join
            (select max(col3) as maxcol3
             from T1 t11
             where col2 = 12345
            ) tmax
            on T1.col3 = tmax.maxcol3 and
               T1.col2 = 12345
         set T1.col1 = 500;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法