使用JOIN的MySQL语法

时间:2013-07-04 12:49:02

标签: mysql sql join syntax many-to-many

我的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

1 个答案:

答案 0 :(得分: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'