這是建立個人表的腳本: 數據庫
CREATE TABLE clients ( client_i INT(11), PRIMARY KEY (client_id) ); CREATE TABLE projects ( project_id INT(11) UNSIGNED, client_id INT(11) UNSIGNED, PRIMARY KEY (project_id) ); CREATE TABLE posts ( post_id INT(11) UNSIGNED, project_id INT(11) UNSIGNED, PRIMARY KEY (post_id) );
在個人PHP代碼中,刪除客戶端時,我要刪除全部項目帖子: post
DELETE FROM posts INNER JOIN projects ON projects.project_id = posts.project_id WHERE projects.client_id = :client_id;
posts表沒有外鍵client_id
,只有project_id
。 我想刪除已經過client_id
項目中的帖子。 spa
如今沒法正常工做,由於沒有帖子被刪除。 code
使用子選擇比使用IN
更好的另外一種刪除方法是WHERE
EXISTS
get
DELETE FROM posts WHERE EXISTS ( SELECT 1 FROM projects WHERE projects.client_id = posts.client_id);
使用它而不是JOIN
緣由之一是帶有JOIN
的DELETE
禁止使用LIMIT
。 若是但願刪除塊以避免產生完整的表鎖,則可使用此DELETE WHERE EXISTS
方法添加LIMIT
。 it
嘗試以下: io
DELETE posts.*,projects.* FROM posts INNER JOIN projects ON projects.project_id = posts.project_id WHERE projects.client_id = :client_id;
若是加入對您不起做用,則能夠嘗試此解決方案。 它用於在不使用外鍵+特定條件的狀況下從t1刪除孤立記錄。 即,它從表1中刪除具備空字段「代碼」且在表2中沒有記錄的記錄,並按字段「名稱」進行匹配。 table
delete table1 from table1 t1 where t1.code = '' and 0=(select count(t2.name) from table2 t2 where t2.name=t1.name);
您也能夠像這樣使用ALIAS,它能夠在個人數據庫中使用! t是須要刪除的表! cli
DELETE t FROM posts t INNER JOIN projects p ON t.project_id = p.project_id AND t.client_id = p.client_id
因爲要選擇多個表,所以要刪除的表再也不是惟一的。 您須要選擇 : select
DELETE posts FROM posts INNER JOIN projects ON projects.project_id = posts.project_id WHERE projects.client_id = :client_id
在這種狀況下, table_name1
和table_name2
是同一張表,所以可使用:
DELETE projects FROM posts INNER JOIN [...]
您甚至能夠從兩個表中刪除:
DELETE posts, projects FROM posts INNER JOIN [...]
請注意, order by
和limit
對多表delete無效 。
還應注意,若是爲表聲明別名,則在引用表時必須使用別名:
DELETE p FROM posts as p INNER JOIN [...]