我创建了一个多对多数据库,如下所示:
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的。
最佳答案
您需要添加:
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
Updated fiddle
结果是:
TITLE AMBIENCES
film1 sad happy
film2 sad happy
关于php - MySQL语法,用于显示多对多数据库结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17503870/