MySQL同表更新與查詢衝突

MySQL version: 5.5code

MySQL報錯:ci

You can't specify target table 'document_basic' for update in FROM clause

緣由:MySQL不支持對同表同時更新+查詢
解決方案:查詢結果使用中間表接收,或者使用錶鏈接
 get

# 錯誤:
UPDATE table
SET column = #{newValue}
WHERE id IN (SELECT id FROM table
             WHERE #{condition})

# 使用中間表:
UPDATE table
SET column = #{newValue}
WHERE id IN (SELECT * FROM
                  (SELECT id FROM table
                   WHERE #{condition})temp)

# 使用錶鏈接:
UPDATE table
JOIN table temp ON temp.id = table.id
SET column = #{newValue}
WHERE #{condition}
相關文章
相關標籤/搜索