我写了下面的查询来更新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
答案 0 :(得分:1)
错误非常清楚,告诉您,您正在尝试更新table1
,但在where子句中也使用了table1
。因此,创建一个内部选择和别名它应该可以做到这一点;
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);
答案 1 :(得分:0)
只需使用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';
我怀疑你也可以简化逻辑。