mysql:更新表时出错

vu8f3i0k  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(247)

我写了下面的查询来更新mysql表

update table1
set val_col = 'TRUE'
where id IN(
SELECT ID  
FROM table1 a INNER JOIN
     table2 b
     ON a.a_id = b.a_id
WHERE a.create_dt >= '2017-01-07' AND
      b.check_status = 'FAIL' AND
      b.check_type = 'check1' AND
      b.timestamp_val = (SELECT MAX(b2.timestamp_val)
                         FROM table2 b2
                         WHERE b2.a_id = b.a_id AND
                               b2.check_status = b.check_status AND
                               b2.check_type = b.check_type
                        ));

我犯了个错误 You can't specify target table 'table1' for update in FROM clause

pftdvrlh

pftdvrlh1#

就用一个 JOIN :

UPDATE table1 t1 JOIN
       (SELECT ID  
        FROM table1 a INNER JOIN
             table2 b
             ON a.a_id = b.a_id
        WHERE a.create_dt >= '2017-01-07' AND
              b.check_status = 'FAIL' AND
              b.check_type = 'check1' AND
              b.timestamp_val = (SELECT MAX(b2.timestamp_val)
                                 FROM table2 b2
                                 WHERE b2.a_id = b.a_id AND
                                       b2.check_status = b.check_status AND
                                       b2.check_type = b.check_type
                                )
       ) tt
       ON t1.id = tt.id
    set t1.val_col = 'TRUE';

我想你也可以简化逻辑。

v09wglhw

v09wglhw2#

错误很明显,说明您正在尝试更新 table1 但是 table1 也用于where子句。因此,创建一个内部select并对其进行别名处理就可以了;

update table1
set val_col = 'TRUE'
where id IN(
select * from (
SELECT ID  
FROM table1 a INNER JOIN
     table2 b
     ON a.a_id = b.a_id
WHERE a.create_dt >= '2017-01-07' AND
      b.check_status = 'FAIL' AND
      b.check_type = 'check1' AND
      b.timestamp_val = (SELECT MAX(b2.timestamp_val)
                         FROM table2 b2
                         WHERE b2.a_id = b.a_id AND
                               b2.check_status = b.check_status AND
                               b2.check_type = b.check_type
                        )) aliasTable1);

相关问题