有表films
,actors
和绑定它们的表films_actors
。
创建代码:
CREATE TABLE `actors` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(50) NOT NULL,
`surname` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=9
;
CREATE TABLE `films` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`release` SMALLINT(4) NOT NULL,
`format` VARCHAR(10) NOT NULL,
PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=6
;
CREATE TABLE `films_actors` (
`id_film` INT(11) NOT NULL,
`id_actor` INT(11) NOT NULL,
INDEX `FK_films_actors_actors` (`id_actor`),
INDEX `FK_films_actors_films` (`id_film`),
CONSTRAINT `FK_films_actors_actors` FOREIGN KEY (`id_actor`) REFERENCES `actors` (`id`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT `FK_films_actors_films` FOREIGN KEY (`id_film`) REFERENCES `films` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;
如果我从actors
或films
表中删除数据,则数据将自动从films_actors
表中删除,问题是一个查询是否可以从所有三个查询中删除数据一张桌子吗?
这是我尝试编写的查询,但没有成功。
delete
from films, actors
where actors.id in (
select films_actors.id_actor from films_actors
where films_actors.id_film = 5
) and films.id = films_actors.id_film
答案 0 :(得分:2)
您可以使用删除联接,并在联接中使用子查询来管理IN子句
delete films.*, actors.*
from films
INNER JOIN (
select films_actors.id_actor, id_film
from films_actors
where films_actors.id_film = 5
) t ON films.id = t.id_film
INNER JOIN actors ON actors.id = t.id_actor
答案 1 :(得分:1)
您应该能够:
delete f, a, fa
from films f join
films_actors fa
on fa.id_film = f.id join
actors a
on fa.id_actor = a.id
where f.id = 5;
这似乎很危险,因为演员可能在其他电影中。我假设您只想从f
和fa
中删除。