MySql 多表数据删除

来源:互联网 发布:陶瓷产品设计软件 编辑:程序博客网 时间:2024/05/18 15:51

                               多表数据删除

创建两个数据表,分别是:

create table blog
(
   id                   varchar(40) not null,
   category             varchar(40),
   title                varchar(400),
   content              Text,
   created_time         date,
   primary key (id)
);

create table comment
(
   id                   varchar(40) not null,
   blog_id              varchar(40),
   username             varchar(200),
   content              Text,
   primary key (id)
);

在删除表blog中的某一行数据时,同时删除表comment与表blog对应的数据

1.添加外键约束

alter table comment add constraint FK_blog_id foreign key (blog_id)
      references blog (id) on delete cascade ;

on delete cascade 级联删除

on uupdate cascade  级联更新

2. 通过外键关联

alter table comment add constraint FK_blog_id foreign key (blog_id)
      references blog (id) ;

(1)删除语句:

 delete blog ,comment from blog,comment  where blog.id = comment.blog_id and blog.id=?;

(2) delete blog,comment from blog left join comment on blog.id = comment.blog_id where blog.id=?;

 

原创粉丝点击