nces categories(catid) on delete cascade
on update cascade;
alter table comments add constraint foreign key(newsid) references news(newsid) on delete cascade
on update cascade;
#上面这句的这两个语句就是在添加外键的时候为该表和表之间添加级联操作,即,数据表在删除或更新数据表时,相
关连的表也会同时更新或删除。
例如:
mysql> delete from categories where catid=1;
Query OK, 1 row affected (0.03 sec)
我们删除了类别catid为1的数据即:娱乐新闻,那么有关娱乐新闻的news中的数据double将会被删除,新闻被删除的同时,新闻下的评论也会被同时删除。
如下所示:
mysql> select * from news;
+--------+-------+---------+---------------------+-------+
| newsId | title | content | createTime | catId |
+--------+-------+---------+---------------------+-------+
| 2 | test2 | test2 | 2015-05-19 15:17:03 | 2 |
+--------+-------+---------+---------------------+-------+
1 row in set (0.00 sec)
mysql> select * from comments;
+--------+---------+---------------------+--------+-----------+
| commId | content | createTime | newsId | userIP |
+--------+---------+---------------------+--------+-----------+
| 2 | you | 2015-05-19 15:17:03 | 2 | 127.0.0.1 |
+--------+---------+---------------------+--------+-----------+
1 row in set (0.00 sec)