为什么我在更新sql上遇到此MySql错误

时间:2013-09-01 09:51:27

标签: mysql sql sql-update

我有一张像。

的桌子
 CREATE TABLE `chart` (
      `id` int(10) NOT NULL AUTO_INCREMENT,
      `item` char(6) NOT NULL DEFAULT '',
      `IsLeaf` char(1) NULL DEFAULT 'Y',
      `ParentId` int(10) NOT NULL DEFAULT 0,
      PRIMARY KEY (`id`)
   )

其中parentId包含另一行的id,该行是该行的父

-----------------------------------------------------------------
|   Id  |   item    |   IsLeaf      |  ParentId
-----------------------------------------------------------------
|   1   |   Test1   |   D           |  
-----------------------------------------------------------------
|   2   |   Test3   |   D           |  
-----------------------------------------------------------------
|   3   |   Test4   |   D           |   1
-----------------------------------------------------------------
|   4   |   Test5   |   D           |   1
-----------------------------------------------------------------

我想更新那些至少有一个子行的行。我试过这个

UPDATE chart AS c1 SET c1.IsLeaf='Y' JOIN chart c2 ON c2.ParentId=c1.id;

并收到此错误

[Err] 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 'JOIN chart c2 ON c2.ParentId=c1.id' at line 1

2 个答案:

答案 0 :(得分:3)

你必须在LEFT JOIN之后使用SET KEYWORD并且必须检查null

UPDATE chart AS c1 
LEFT JOIN chart c2 ON c2.ParentId=c1.id SET c1.IsLeaf='Y' 
WHERE c2.id is null;

答案 1 :(得分:2)

尝试使用LEFT JOIN,如下所示: -

 UPDATE chart AS c1 
 LEFT JOIN chart c2 ON c2.ParentId=c1.id 
 SET c1.IsLeaf='Y' WHERE c2.id is null;