简体   繁体   English

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

[英]Nested select statement in MySQL for updating field based upon max value of another field gives error

I want to execute the following SQL statement in PhP. 我想在PhP中执行以下SQL语句。 I have simplified it below. 我在下面简化了它。 I would like to know the MySQL modifications to make it work. 我想知道MySQL的修改使其能够正常工作。 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. 如果相关,我正在使用PDO。

The error given is: 给出的错误是:

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

Use a join instead: 使用一个join ,而不是:

 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM