SQL简单左连接提供错误

时间:2013-01-04 23:34:14

标签: mysql join

我正在使用此处提供的答案:Query rows for which meta data key does not exist

   UPDATE table1
   SET table1.id = table2.id
   FROM table1
   LEFT JOIN table2 ON table1.id=table2.id
   WHERE table.id IS NULL

我希望将表1中的所有id设置为table2中相应的id,只有table1的id为null,但这会给出“mysql错误”。

有什么想法? 提前谢谢。

2 个答案:

答案 0 :(得分:1)

与大多数数据库一样,MySQL有一个unique syntax用于连接和更新:

UPDATE table1
LEFT JOIN table2 ON table1.id=table2.id
SET table1.id = table2.id
WHERE table1.id IS NULL

答案 1 :(得分:0)

您无法加入UPDATE语句(编辑 - 也许您可以)。您需要一个只返回一行的子选择。如果id是连接列,你的查询也没有意义 - 我假设你正在加入别的东西。

我认为这样的事情是正确的(没有测试过)。

UPDATE table1 outer
SET id = (
    SELECT table2.id 
    FROM table2 JOIN table1 USING(join_column) -- or ON if the columns aren't the same
    WHERE join_column = outer.join_column
)
WHERE id is null
相关问题