简体   繁体   English

使用联接的SQL查询更新

[英]SQL Query Update using a join

Here is my SELECT statement that lists what I am trying to change; 这是我的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')

I want to replace all the 'incorrect gid's with the 'correct gid's using an UPDATE statement. 我想使用UPDATE语句将所有“不正确的gid”替换为“正确的gid”。

This is the UPDATE statement I have tried but cannot get to work; 这是我尝试过的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')

Basically, all the rows that are children have an incorrect gid (group id) and need to be fixed. 基本上,所有属于子级的行都具有不正确的gid(组ID),需要进行修复。 But all rows that refer to the parent (as parent and children are in the same table) will have a correct group id. 但是,所有引用父项的行(因为父项和子项在同一表中)将具有正确的组ID。

So I have to join up the parents groupid, to each child row.. 因此,我必须将父母groupid加入每个孩子行中。

The correct syntax in MySQL: 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM