dousi5358 2009-09-11 18:56
浏览 119
已采纳

如何在MySQL中实现级联数据的级联删除?

I'm working on a project that has categories/subcategories. The database table for this is unique, with the following structure:

CREATE TABLE IF NOT EXISTS `categories` (
  `id` int(11) NOT NULL auto_increment,
  `publish` tinyint(1) NOT NULL default '0',
  `parent_id` int(11) NOT NULL default '0',
  `description` text NOT NULL,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

So, in case the category is a "base" one, the parent_id is zero, and if the category has a parent, it herds the parent id. What I want to know is this: I need to delete everything above and related with a category when choosing that option, a cascade-like deletion, but I only have this table (no foreign keys). How do I do that? (Without a large amount of queries.)

  • 写回答

2条回答 默认 最新

  • dongluojiao6322 2009-09-11 18:59
    关注
    • You can write a trigger to do it.

      DELIMITER //
      CREATE TRIGGER CatDelete AFTER DELETE ON categories
      FOR EACH ROW BEGIN
        DELETE FROM categories WHERE parent_id = old.id;
      END//
      DELIMITER ;
      
    • You can ALTER your MyISAM tables to InnoDB, and then define foreign key constraints with the ON DELETE CASCADE option.

      ALTER TABLE categories ENGINE=InnoDB;
      ALTER TABLE categories ADD CONSTRAINT 
        FOREIGN KEY (parent_id) REFERENCES categories (id) ON DELETE CASCADE;
      

    Re your comment, the first thing I'd check is if you have some orphan categories, that is with parent_id pointing to a non-existant row. That would prevent you from creating the constraint.

    SELECT c1.*
    FROM categories c1
    LEFT OUTER JOIN categories c2
      ON (c1.parent_id = c2.id)
    WHERE c2.id IS NULL;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改