[英]SQL Query Update using a 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。
因此,我必須將父母groupid加入每個孩子行中。
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.