MySQL多表記錄刪除技巧
同時從多個MySQL表中刪除記錄是一項複雜的任務。直接使用包含多個表引用的WHERE子句的DELETE語句通常會失敗。例如,以下程式碼:
<code class="language-sql">DELETE FROM `pets` p, `pets_activities` pa WHERE p.`order` > :order AND p.`pet_id` = :pet_id AND pa.`id` = p.`pet_id`</code>
通常會產生類似這樣的錯誤:
正確的做法是使用JOIN關鍵字。修改後的程式碼如下:Uncaught Database_Exception [1064]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'p, pets_activities ...'
<code class="language-sql">DELETE p, pa FROM pets p JOIN pets_activities pa ON pa.id = p.pet_id WHERE p.order > :order AND p.pet_id = :pet_id</code>
表中的記錄,可以使用以下程式碼:pets_activities
<code class="language-sql">DELETE pa FROM pets_activities pa JOIN pets p ON pa.id = p.pet_id WHERE p.order > :order AND p.pet_id = :pet_id</code>
以上是如何正確刪除MySQL多個表中的記錄?的詳細內容。更多資訊請關注PHP中文網其他相關文章!