1

我创建了一个这样的多对多数据库:

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

CREATE TABLE Ambiences (  
id INT NOT NULL AUTO_INCREMENT,   
PRIMARY KEY(id),  
ambienceName VARCHAR(255));

CREATE TABLE Films_Ambiences (
film_id INT NOT NULL,  
ambience_id INT NOT NULL,  
PRIMARY KEY (film_id, ambience_id),  
FOREIGN KEY (film_id) REFERENCES Films(id) ON UPDATE CASCADE,  
FOREIGN KEY (ambience_id) REFERENCES Ambiences(id) ON UPDATE CASCADE);

现在:我插入了一些数据并加入了表格以获得:

╔════════╦════╦══════════╗  
║ Title  ║ id ║ Ambience ║  
╠════════╬════╬══════════╣  
║ film_1 ║  1 ║ Funny    ║
║ film_1 ║  1 ║ Sad      ║
║ film_2 ║  2 ║ Funny    ║
║ film_2 ║  2 ║ Sad      ║
╚════════╩════╩══════════╝  

但是,我的目标是在一行显示film_1,在第二行显示film_2,如下所示:

╔════════╦════╦══════════╗  
║ Title  ║ id ║ Ambience ║  
╠════════╬════╬══════════╣  
║ film_1 ║  1 ║ Funny,Sad║
║ film_2 ║  2 ║ Funny,Sad║
╚════════╩════╩══════════╝  

我正在尝试使用GROUP_CONCAT,但我得到了:

╔════════╦════╦════════════════════════╗
║ Title  ║ id ║        Ambience        ║
╠════════╬════╬════════════════════════╣
║ film_1 ║  1 ║ funny, funny, sad, sad ║
╚════════╩════╩════════════════════════╝ 

它将所有行合并为一个。这是一个SQLFiddle

4

1 回答 1

2

您需要添加GROUP BY

SELECT title,
       GROUP_CONCAT(ambienceName SEPARATOR ' ') AS ambiences
FROM   Films AS f 
   INNER JOIN Films_Ambiences as fa
         ON f.id = fa.film_id           
   INNER JOIN Ambiences AS a
         ON a.id = fa.ambience_id
GROUP  BY title

更新的小提琴

结果是:

TITLE   AMBIENCES
film1   sad happy
film2   sad happy
于 2013-07-06T14:29:28.210 回答