使用连接的SQL查询更新

时间:2014-08-29 11:39:23

标签: mysql sql join set left-join

这是我的SELECT语句,列出了我想要改变的内容;

SELECT

t1.`qid`,
t1.`gid` as 'incorrect gid',
t1.`question` as 'subquestion',
t1.`parent_qid`,

t2.`qid`,
t2.`gid` as 'correct gid',
t2.`question`

FROM `questions` as t1

LEFT JOIN `questions` as t2 ON t1.`parent_qid` = t2.`qid`

WHERE t1.`sid` = '33844' AND t1.`gid` NOT IN ('1306','1317','1319','1320','1321','1322','1323','1324','1325','1326','1327','1328','1329','1330','1331','1332','1333','1334','1335''1334','1335','1336', '1337','1338','1339','1340')

我想使用UPDATE语句将所有'不正确的gid'替换为'正确的gid'。

这是我尝试但无法开始工作的UPDATE语句;

UPDATE `questions` as t1 

SET `gid` = t2.`gid`

FROM

`questions` as t1
LEFT JOIN
`questions` as t2 ON t1.`parent_qid` = t2.`qid`

WHERE t1.`sid` = '33844' AND t1.`gid` NOT IN ('1306','1317','1319','1320','1321','1322','1323','1324','1325','1326','1327','1328','1329','1330','1331','1332','1333','1334','1335''1334','1335','1336', '1337','1338','1339','1340')

基本上,所有子行都有一个不正确的gid(组ID),需要修复。但是所有引用父级的行(作为父级和子级都位于同一个表中)将具有正确的组ID。

所以我必须加入父母的团体,每个孩子的行......

1 个答案:

答案 0 :(得分:2)

MySQL中的正确语法:

UPDATE `questions` as t1 LEFT JOIN
       `questions` as t2 ON t1.`parent_qid` = t2.`qid`
    SET t1.`gid` = t2.`gid`
WHERE t1.`sid` = '33844' AND
      t1.`gid` NOT IN ('1306','1317','1319','1320','1321','1322','1323','1324','1325','1326','1327','1328','1329','1330','1331','1332','1333','1334','1335''1334','1335','1336', '1337','1338','1339','1340')