我想用其他列更新列...
我的代码:
update Table1 set Table1.number = Table2.number from Table1 where Table2.Table1Id= Table1.id;
错误:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from Table1 where Table2.Table1Id= Table1.id' at line 1
答案 0 :(得分:1)
执行此更新的ANSI方法是:
UPDATE Table1
SET Table1.number = ( SELECT Table2.number
FROM Table2
WHERE Table2.Table1Id= Table1.id
)
WHERE EXISTS
( SELECT Table2.number
FROM Table2
WHERE Table2.Table1Id= Table1.id
);
或者专有的MySQL UPDATE / JOIN语法是:
UPDATE Table1
INNER JOIN Table2
ON Table2.Table1Id= Table1.id;
SET Table1.number = Table2.number;
这里的ANSI语法很差,特别是如果你需要更新多个字段,例如:
UPDATE Table1
SET Table1.number = ( SELECT Table2.number
FROM Table2
WHERE Table2.Table1Id= Table1.id
),
Table1.number2 = ( SELECT Table2.number2
FROM Table2
WHERE Table2.Table1Id= Table1.id
),
Table1.number3 = ( SELECT Table2.number3
FROM Table2
WHERE Table2.Table1Id= Table1.id
)
WHERE EXISTS
( SELECT Table2.number
FROM Table2
WHERE Table2.Table1Id= Table1.id
);
我认为即使是那些坚持使用ANSI兼容代码的人中最坚定的也很难通过一个简单的连接为此做好准备!
答案 1 :(得分:0)
在MySQL中,您可以在join
:
update
update Table1 join
Table2
on Table2.Table1Id = Table1.id
set Table1.number = Table2.number ;
这似乎是您的语法意图。