MySQL显示多对多关系的结果

时间:2013-07-04 22:42:22

标签: php html mysql sql many-to-many

我已经与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)";

所以可能会有一部有2种或更多情绪的电影。让他们成为$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一样使用表格类型和氛围,我试图用特定的流派和氛围进行搜索:

"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')"

1 个答案:

答案 0 :(得分: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来解决这个问题 - 我还修复了你的架构中的一些拼写错误。