[英]SQL DELETE with INNER JOIN
有2個表, spawnlist
和npc
,我需要從spawnlsit
刪除數據。 npc_templateid = n.idTemplate
是唯一“連接”表格的東西。 我試過這個腳本,但它不起作用。
我試過這個:
DELETE s FROM spawnlist s
INNER JOIN npc n ON s.npc_templateid = n.idTemplate
WHERE (n.type = "monster");
在第一行添加.*
到s
。
嘗試:
DELETE s.* FROM spawnlist s
INNER JOIN npc n ON s.npc_templateid = n.idTemplate
WHERE (n.type = "monster");
如果數據庫是InnoDB,那么在刪除時使用外鍵和級聯可能是更好的主意,這可以做你想要的,也不會導致存儲冗余數據。
對於這個例子,我認為你不需要第一個:
DELETE s
FROM spawnlist AS s
INNER JOIN npc AS n ON s.npc_templateid = n.idTemplate
WHERE n.type = "monster";
在刪除之前選擇行可能是一個更好的主意,因此您確定刪除了您想要的內容:
SELECT * FROM spawnlist
INNER JOIN npc ON spawnlist.npc_templateid = npc.idTemplate
WHERE npc.type = "monster";
您還可以在此處查看MySQL刪除語法: http : //dev.mysql.com/doc/refman/5.0/en/delete.html
如果數據庫是InnoDB,則不需要在刪除時進行連接。 只要
DELETE FROM spawnlist WHERE spawnlist.type = "monster";
可用於刪除與其他表中的外鍵鏈接的所有記錄,為此,您必須首先在設計時鏈接表。
CREATE TABLE IF NOT EXIST spawnlist (
npc_templateid VARCHAR(20) NOT NULL PRIMARY KEY
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXIST npc (
idTemplate VARCHAR(20) NOT NULL,
FOREIGN KEY (idTemplate) REFERENCES spawnlist(npc_templateid) ON DELETE CASCADE
)ENGINE=InnoDB;
如果你使用MyISAM,你可以刪除像這樣加入的記錄
DELETE a,b
FROM `spawnlist` a
JOIN `npc` b
ON a.`npc_templateid` = b.`idTemplate`
WHERE a.`type` = 'monster';
在第一行我初始化了兩個臨時表來刪除記錄,在第二行我已經將存在表分配給a和b但是在這里我已經將兩個表與join關鍵字鏈接在一起,並且我匹配了主鍵和外鍵對於兩個創建鏈接的表,在最后一行我已按字段過濾記錄以刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.