CREATE TABLE buildings (
building_no INT PRIMARY KEY AUTO_INCREMENT,
building_name VARCHAR(255) NOT NULL,
address VARCHAR(255) NOT NULL
)
CREATE TABLE rooms (
room_no INT PRIMARY KEY AUTO_INCREMENT,
room_name VARCHAR(255) NOT NULL,
building_no INT NOT NULL,
FOREIGN KEY (building_no)
REFERENCES buildings (building_no)
ON DELETE CASCADE
)
当执行
DELETE FROM buildings
WHERE
building_no = 2的时候,rooms表中的building_no =2的记录都会被删掉。
设定外键为级联删除就可以了。alter table B add constraint fk_ID foreign key (ID) references A(ID) on delete cascade
这样只需:delete from A where ID=nnnn就可以自动删除对应B表内容了。
通过外键无法实现同步更新。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)