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 

我想在PhP中执行以下SQL语句。 我在下面简化了它。 我想知道MySQL修改使其工作。 我尝试了一些给表中的别名,但它不起作用: p>

  update T1 set col1 = 500 
其中col2 = 12345和
 col3 =(选择最大值 (col3)来自T1,其中col2 = 12345)
  code>  pre> 
 
 

我想更新一列具有最大值的记录。 整个查询中只涉及一个表。 我正在使用PDO,如果这是相关的。 p>

给出的错误是: p>

 #1093  - 您无法指定目标表 'T1'用于FROM子句中的更新
  code>  pre> 
  div>

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;