日期:2014-05-16  浏览次数:20869 次

如何使A表某【信息】删除B表【相关信息】也强制删除(A的主键是B的外键)
我有两个表,代码如下,怎么样可以使booking表中某条信息被删除后,information表中相关信息也强制删除,不要重新建表,在cmd里面怎么写SQL语句?

SQL code

create table booking(
 o_id bigint(20) not null primary key,
 o_user int(10) not null,
 o_time varchar(50) not null,
 o_state varchar(10) not null,
 o_delivery varchar(50),
 o_ems varchar(20),
 o_number int(20),
 o_total float(6,2) not null,
 foreign key(o_user) references user(u_id)
 )engine=InnoDB charset=utf8;


create table information(
 i_id int(10) not null auto_increment primary key,
 i_orderid bigint(20) not null,
 i_name varchar(50) not null,
 i_number int(10) not null,
 i_price float(6,2) not null,
 foreign key(i_orderid) references booking(o_id)      //外键
 )engine=InnoDB charset=utf8;



------解决方案--------------------
create table booking(
 o_id bigint(20) not null primary key,
 o_user int(10) not null,
 o_time varchar(50) not null,
 o_state varchar(10) not null,
 o_delivery varchar(50),
 o_ems varchar(20),
 o_number int(20),
 o_total float(6,2) not null
 )engine=InnoDB charset=utf8;


create table information(
 i_id int(10) not null auto_increment primary key,
 i_orderid bigint(20) not null,
 i_name varchar(50) not null,
 i_number int(10) not null,
 i_price float(6,2) not null,
 CONSTRAINT `i_orderid` FOREIGN KEY (`i_id`) REFERENCES `booking` (`o_id`) ON DELETE CASCADE ON UPDATE CASCADE
 )engine=InnoDB charset=utf8;


------解决方案--------------------
如果不想重建 可以这样
1.找出原来建立好的外键约束 
SQL code
SELECT
ke.referenced_table_name parent,
ke.table_name child,
ke.REFERENCED_COLUMN_NAME parent_column,   
ke.column_name child_column,
ke.constraint_name
FROM
information_schema.KEY_COLUMN_USAGE ke
WHERE
ke.referenced_table_name IS NOT NULL
and ke.referenced_table_name = 'booking'
and ke.REFERENCED_COLUMN_NAME = 'o_id'
and ke.REFERENCED_TABLE_SCHEMA = '你的数据库名字'
ORDER BY ke.referenced_table_name;