P粉2371257002023-08-28 13:59:47
您可以透過三個步驟完成此操作:
CREATE TABLE test2 AS SELECT PersId FROM pers p WHERE ( chefID IS NOT NULL OR gehalt < ( SELECT MAX ( gehalt * 1.05 ) FROM pers MA WHERE MA.chefID = p.chefID ) )
...
UPDATE pers P SET P.gehalt = P.gehalt * 1.05 WHERE PersId IN ( SELECT PersId FROM test2 ) DROP TABLE test2;
或
UPDATE Pers P, ( SELECT PersId FROM pers p WHERE ( chefID IS NOT NULL OR gehalt < ( SELECT MAX ( gehalt * 1.05 ) FROM pers MA WHERE MA.chefID = p.chefID ) ) ) t SET P.gehalt = P.gehalt * 1.05 WHERE p.PersId = t.PersId
P粉4818158972023-08-28 13:51:38
問題在於,無論出於何種愚蠢的原因,MySQL 不允許您編寫以下查詢:
UPDATE myTable SET myTable.A = ( SELECT B FROM myTable INNER JOIN ... )
也就是說,如果您要對錶執行UPDATE
/INSERT
/DELETE
操作,則無法在內部查詢(但您可以引用外部表中的欄位...)
解決方案是將子查詢中的myTable
實例替換為(SELECT * FROM myTable)
,如下所示
UPDATE myTable SET myTable.A = ( SELECT B FROM (SELECT * FROM myTable) AS something INNER JOIN ... )
這顯然會導致必要的欄位被隱式複製到臨時表中,因此這是允許的。
我找到了這個解決方案這裡。該文章的註解: