SQL DELETE with INNER JOIN

前端 未结 3 473
慢半拍i
慢半拍i 2020-12-02 17:39

There are 2 tables, spawnlist and npc, and I need to delete data from spawnlsit. npc_templateid = n.idTemplate is the onl

3条回答
  •  日久生厌
    2020-12-02 18:39

    if the database is InnoDB you dont need to do joins in deletion. only

    DELETE FROM spawnlist WHERE spawnlist.type = "monster";
    

    can be used to delete the all the records that linked with foreign keys in other tables, to do that you have to first linked your tables in design time.

    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;
    

    if you uses MyISAM you can delete records joining like this

    DELETE a,b
    FROM `spawnlist` a
    JOIN `npc` b
    ON a.`npc_templateid` = b.`idTemplate`
    WHERE a.`type` = 'monster';
    

    in first line i have initialized the two temp tables for delet the record, in second line i have assigned the existance table to both a and b but here i have linked both tables together with join keyword, and i have matched the primary and foreign key for both tables that make link, in last line i have filtered the record by field to delete.

提交回复
热议问题