0

我的 MySQL 数据库中有以下表格:

CREATE TABLES Films (  
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),   
Title VARCHAR(255)),  

CREATE TABLE Genres (  
id INT NOT NULL AUTO_INCREMENT,   
PRIMARY KEY(id),  
Name VARCHAR(255))

CREATE TABLE Films_Genres (
film_id INT NOT NULL,  
genre_id INT NOT NULL,  
PRIMARY KEY (film_id,genre_id),  
FOREIGN KEY (film_id) REFERENCES Films(id) ON UPDATE CASCADE,  
FOREIGN KEY (genre_id) REFERENCES Genres(id) ON UPDATE CASCADE)";  

我想搜索具有特定类型的电影存储在$genre. 我也想选择这个流派的名称(不要问我为什么;))。我知道如何做第一部分。我试图实现第二部分,JOIN但我的语法有问题:

SELECT * FROM Films WHERE id IN (    
SELECT film_id FROM Films_Genres  
WHERE genre_id IN SELECT id FROM Genres WHERE Name = '$genre'))  
JOIN Genres ON Name = '$genre'

错误信息:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'JOIN Genres ON Name = 'Action'' at line 1

4

1 回答 1

0

应该这样写:

SELECT * 
FROM Films 
JOIN Genres ON id = genre_id
WHERE id IN 
(    
   SELECT film_id 
   FROM Films_Genres  
   WHERE genre_id IN (SELECT id FROM Genres WHERE Name = '$genre')
)   
AND Name = '$genre';

JOIN应该是后FROM

或者您可以JOIN直接使用表而不是这些IN谓词:

SELECT * 
FROM Films AS f
INNER JOIN Films_Genres AS fg ON f.id = fg.film_id
INNER JOIN Genres       AS g  ON g.id = fg.genre_id

WHERE g.Name = '$genre'
于 2013-07-04T12:51:37.843 回答