0

我在服务器上有一个数据库,我会创建这些带有约束的表。这是关系 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 表中删除连接的行。但它不起作用!为什么?

谢谢大家,对不起我的英语!

4

1 回答 1

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)
于 2016-07-15T16:25:58.263 回答