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条)

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?