我在服务器上有一个数据库,我将创建具有约束的这些表。这是关系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表中将删除连接的行。但这不起作用!为什么?
谢谢大家,对不起我的英语!
最佳答案
如果要删除外键用户中的相关记录
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)
关于mysql - FOREIGN KEY CONSTRAINT的定义不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19954588/