如果我有两张这样的表:
CREATE TABLE Director
(
`DirectorNr` INTEGER NOT NULL,
`First Name` VARCHAR (20),
`Last Name` VARCHAR (30),
`Age` INTEGER,
`Movies` INTEGER,
PRIMARY KEY(DirectorNr)
);
CREATE TABLE Movies
(
`MovieNr` INTEGER NOT NULL,
`Title` VARCHAR (100),
`Genre` VARCHAR (30),
`USK` INTEGER,
`Director` INTEGER NOT NULL,
`Length` INTEGER,
`Release` DATE,
PRIMARY KEY (MovieNr),
FOREIGN KEY (Director)
REFERENCES Director (DirectorNr)
);
INSERT INTO Director
VALUES (1, 'Peter', 'Jackson', 52, 17);
INSERT INTO Movies
VALUES (1, 'The Hobbit: An Unexpected Journey', 'Fantasy', 12, 1, 169, '2012/12/12');
如何通过外键使用SELECT?
获取Director的名称这样的事情:
SELECT `Director.First Name` `Director.Last Name` FROM Movies ...
答案 0 :(得分:1)
加入director
表并指定on
条件
SELECT m.title, d.`First Name`, d.`Last Name`
FROM Movies m
JOIN Director d ON m.Director = d.DirectorNr
注意:使用该设计,您只能拥有一个电影导演。
要转义表名或列名,只能使用元素名称周围的反引号而不是表和列的组合
错误
`director.first name`
正确
director.`first name`
答案 1 :(得分:1)
SELECT d.`First Name`, d.`Last Name` FROM Director d
WHERE DirectorNr IN (SELECT Director FROM Movies WHERE Director=value );
答案 2 :(得分:-1)
从电影m,导演d中选择m.Title,d.FirstName,其中m.Director = d.DirectorNr