我在服务器上有一个DB,我会用约束创建这些表。这是关系N:M
的“子表”的代码CREATE TABLE IF NOT EXISTS `Sql183209_2`.`ArtistiXGruppi` (
`idArtistaXGruppo` INT NOT NULL AUTO_INCREMENT,
`Artista` INT NOT NULL,
`Gruppo` INT NOT NULL,
`CapoOrchestra` TINYINT(1) NULL,
`KmDaSede` FLOAT NULL,
PRIMARY KEY (`idArtistaXGruppo`),
INDEX `Gruppo_idx` (`Gruppo` ASC),
UNIQUE INDEX `uniqe` (`Artista` ASC, `Gruppo` ASC),
INDEX `Artista_idy` (`Artista` ASC),
CONSTRAINT `Artista`
FOREIGN KEY (`Artista`)
REFERENCES `Sql183209_2`.`Artisti` (`idArtista`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `Gruppo`
FOREIGN KEY (`Gruppo`)
REFERENCES `Sql183209_2`.`Gruppi` (`idGruppo`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB;
以下是其他两个表的代码。
CREATE TABLE IF NOT EXISTS `Sql183209_2`.`Artisti` (
`idArtista` INT NOT NULL AUTO_INCREMENT,
`Codice` VARCHAR(45) NULL,
`Matricola` VARCHAR(45) NULL,
`CodiceFiscale` VARCHAR(16) NULL,
PRIMARY KEY (`idArtista`),
UNIQUE INDEX `CodiceFiscale_UNIQUE` (`CodiceFiscale` ASC),
UNIQUE INDEX `Codice_UNIQUE` (`Codice` ASC),
UNIQUE INDEX `Matricola_UNIQUE` (`Matricola` ASC))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `Sql183209_2`.`Gruppi` (
`idGruppo` INT NOT NULL,
`Codice` VARCHAR(45) NOT NULL,
`Nome` VARCHAR(100) NULL,
PRIMARY KEY (`idGruppo`),
UNIQUE INDEX `Codice_UNIQUE` (`Codice` ASC),
CONSTRAINT `agenzia`
FOREIGN KEY (`Agenzia`)
REFERENCES `Sql183209_2`.`Agenzie` (`idAgenzia`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
我在表Artisti和Gruppi中制作了一些插页。当我在ArtistiXGruppi表中插入一些数据并且在我删除相关表中的Artist或Group行之一后,我希望在ArtistiXGruppi表中删除连接的行。但它不起作用!为什么呢?
感谢所有人,对不起我的英语!
答案 0 :(得分:0)
如果要删除外键用户中的相关记录
ON DELETE CASCADE
可能是因为你使用了
ON DELETE NO ACTION
mysql> drop table user;
Query OK, 0 rows affected (0.01 sec)
mysql> CREATE TABLE USER
-> (
-> id int,
-> name VARCHAR(50),
-> gender VARCHAR(2),
-> dateofbirth DATE,
-> song_id int,
-> ratings int
-> );
Query OK, 0 rows affected (0.01 sec)
mysql> drop table song;
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE song
-> (
-> id int primary key ,
-> name VARCHAR(50),
-> lengthofsong int,
-> album_id int
-> );
Query OK, 0 rows affected (0.01 sec)
mysql> ALTER TABLE USER ADD CONSTRAINT fk_song_id FOREIGN KEY(song_id) REFERENC
ES song(id) on delete cascade;
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> insert into song values(1,'AA',1,1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into user values (1,'UU','ma',null,1,1);
Query OK, 1 row affected (0.00 sec)
mysql> delete from song where id = 1;
Query OK, 1 row affected (0.00 sec)
mysql> select * from user;
Empty set (0.00 sec)