如何根据其他表中的数据查询sql中的更新

时间:2017-05-10 17:16:28

标签: mysql sql

我有2张桌子。 例如:

table1
ID, data_static1, name1
1      8          Muna
2      1          Andi
3      7          null

table2
ID, data_static2, name2
1       0         Aji
2       1         Andi
3       2         max
4       3         nadine
5       4         Rio
6       5         Panji
7       6         Eko
8       7         Pan
9       8         Muna

我想根据name1table1table1.data_static1相同的最大ID来更新table1中的列table2.data_static2

我希望结果如下

table1
ID, data_static1, name
1      8          Muna
2      1          Andi
3      7          Pan

我尝试过以下代码

mysql> UPDATE theDB.table1 SET name1=(SELECT name2 FROM table2 WHERE data_static2=(SELECT data_static1 From table1 WHERE ID IN(SELECT MAX(ID) FROM table1))) WHERE table1.ID IN(SELECT MAX(table1.ID) FROM theDB.table1);

我收到错误消息

ERROR 1093 (HY000): You can't specify target table 'table1' for update in FROM clause

1 个答案:

答案 0 :(得分:1)

最简单的解决方案是使用相关的子查询:

update table1 t1
set name1 = (
        select name2
        from table2 t2
        where t1.data_static1 = t2.data_static2
        order by id desc limit 1
        );

您也可以使用JOIN:

update table1 t1
join (
    select *
    from table2 t
    join (
        select data_static2,
            max(id) as id
        from table2
        group by data_static2
        ) t2 using (data_static2, id)
    ) t2 on t1.data_static1 = t2.data_static2
set t1.name1 = t2.name2;