0

我已经建立了一个包含 3 个表的多对多关系数据库:

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

CREATE TABLE Moods (  
id INT NOT NULL AUTO_INCREMENT,   
PRIMARY KEY(id),  
mood_name VARCHAR(255))

CREATE TABLE Films_Moods (
film_id INT NOT NULL,  
mood_id INT NOT NULL,  
PRIMARY KEY (film_id, mood_id),  
FOREIGN KEY (film_id) REFERENCES Films(id) ON UPDATE CASCADE,  
FOREIGN KEY (mood_id) REFERENCES Moods(id) ON UPDATE CASCADE)";

所以可能有一部电影有两种或更多的情绪。让他们成为$mood1$mood2

我想在表格中将所选电影显示为单行,例如以下列方式:

<table>
<tr>
    <th>Title</th>
    <th>Mood(s)</th>
</tr>

和PHP代码:

while($row = mysqli_fetch_array($result))
{

        echo "<tr>";
        echo "<td>" . $row['Title'] . "</td>";
        echo "<td>" . $row['Moods'] . "</td>";
        echo "</tr>";
}

问题是:如何获得$row['Moods']它会以某种方式结合两行:
film_1 moodName_1
film_1 moodName_2

或者我想要实现的目标是否有替代方法?

编辑

实际上,我使用类似于 Moods 的表 Genres 和 Ambiences 并且我尝试使用特定的 Genres 和 Ambiences 进行搜索:

"SELECT *,GROUP_CONCAT(ambienceName SEPARATOR ' ') AS ambiences 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
        INNER JOIN Films_Ambiences as fa ON f.id = fa.film_id           
        INNER JOIN Ambiences AS a ON a.id = fa.ambience_id
        WHERE g.Name LIKE '$genre' AND (a.ambienceName LIKE '$ambience1' OR a.ambienceName LIKE '$ambience2')"
4

1 回答 1

2
SELECT title,GROUP_CONCAT(mood_name SEPARATOR ' ') AS moods
FROM films 
JOIN films_moods ON films.id=films_moods.film_id
JOIN moods ON films_moods.mood_id=moods.id
GROUP BY title

您可以通过访问http://sqlfiddle.com/#!2/c6dd3/14/0来解决这个问题- 我还修复了您架构中的几个拼写错误。

于 2013-07-04T22:45:42.073 回答