从多个表中选择/加入,其中tbl1.x = tbl2.x = tbl3.x

时间:2015-08-02 12:51:29

标签: mysql sql database relational-database

我有一个电影数据库,需要执行一个查询,返回由同一个人编写,指导和制作的所有电影。

我在电影之间存在很多关系 - >制作人,电影 - >导演和电影 - >名为movie_director,movie_producer和movie_writer的作家。这些表有一个名为persons的表的外键和一个电影表的外键。

如何选择 one 且制作人,导演和作家相同的电影?我尝试过这个select语句,但它返回了很多重复项:

SELECT movie_director.name
from movie_director, 
     movie_producer, 
     movie_writer
where movie_producer.name = movie_director.name = movie_writer.name;

创建movie_director:

CREATE TABLE `movie_director` (
  `title` VARCHAR(100) NOT NULL,
  `year` int NOT NULL,
  `name` VARCHAR(100) NOT NULL,
  PRIMARY KEY (`title`, `year`, `name`),
  INDEX `fk_movies_has_directors_name_idx` (`name` ASC),
  INDEX `fk_movies_has_directors_titleyear_idx` (`title` ASC, `year` ASC),
  CONSTRAINT `fk_movies_has_directors_titleyear`
    FOREIGN KEY (`title` , `year`)
    REFERENCES `mdb`.`movies` (`title` , `year`)
    ON DELETE cascade
    ON UPDATE cascade,
  CONSTRAINT `fk_movies_has_directors_name`
    FOREIGN KEY (`name`)
    REFERENCES `mdb`.`directors` (`name`)
    ON DELETE cascade
    ON UPDATE cascade)
    ENGINE INNODB;

创建movie_director:

CREATE TABLE `movie_producer` (
 `title` VARCHAR(100) NOT NULL,
  `year` int NOT NULL,
  `name` VARCHAR(100) NOT NULL,
  PRIMARY KEY (`title`, `year`, `name`),
  INDEX `fk_movies_has_producers_name_idx` (`name` ASC),
  INDEX `fk_movies_has_producers_titleyear_idx` (`title` ASC, `year` ASC),
  CONSTRAINT `fk_movies_has_producers_titleyear`
    FOREIGN KEY (`title` , `year`)
    REFERENCES `mdb`.`movies` (`title` , `year`)
    ON DELETE cascade
    ON UPDATE cascade,
  CONSTRAINT `fk_movies_has_producers_name`
    FOREIGN KEY (`name`)
    REFERENCES `mdb`.`producers` (`name`)
    ON DELETE cascade
    ON UPDATE cascade)
    ENGINE INNODB;

创建movie_writer:

CREATE TABLE `movie_writer` (
 `title` VARCHAR(100) NOT NULL,
  `year` int NOT NULL,
  `name` VARCHAR(100) NOT NULL,
  PRIMARY KEY (`title`, `year`, `name`),
  INDEX `fk_movies_has_writers_name_idx` (`name` ASC),
  INDEX `fk_movies_has_writers_titleyear_idx` (`title` ASC, `year` ASC),
  CONSTRAINT `fk_movies_has_writers_titleyear`
    FOREIGN KEY (`title` , `year`)
    REFERENCES `mdb`.`movies` (`title` , `year`)
    ON DELETE cascade
    ON UPDATE cascade,
  CONSTRAINT `fk_movies_has_writers_name`
    FOREIGN KEY (`name`)
    REFERENCES `mdb`.`writers` (`name`)
    ON DELETE cascade
    ON UPDATE cascade)
    ENGINE INNODB;

感谢所有帮助或指向有用信息的链接!

2 个答案:

答案 0 :(得分:1)

首先,您需要将movies表与所有其他三个表联系起来,以查找任何电影的producer ,director and writer名称 然后你可以过滤所有字段名称相同的结果。

作为旁注从不使用旧式逗号分隔连接始终使用正确的Inner Join语法来连接两个或多个表

SELECT     movie_director.NAME 
FROM       movies m 
INNER JOIN movie_director md 
ON         m.movieid = md.movieid 
INNER JOIN movie_producer mp 
ON         m.movieid = mp.movieid movie_writer mw 
ON         m.movieid = mp.movieid 
WHERE      mp.NAME=md.NAME 
AND        mp.NAME=mw.NAME

答案 1 :(得分:0)