如何制作电影和流派列表 - MySQL加入多对多(我应该?)和PHP? 或者做其他方式?
示例:
在MySQL中:
Table 1:
movie_id | movie_title
1______ | title_movie_1
2______ | title_movie_2
3______ | title_movie_3
Table 2:
genre_id | genre_title
1______ | title_genre_1
2______ | title_genre_2
3______ | title_genre_3
Table 3:
id | movie_id | genre_1
1_ | __1____ | _1
2_ | __1____ | _2
3_ | __2____ | _1
4_ | __2____ | _3
5_ | __3____ | _1
6_ | __3____ | _3
7_ | __3____ | _2
结果PHP:
Movie: <a href="movie/1 (id_movie)">title_movie_1 _/a>
Genre:
<a href="genre/1 (id_genre)">title_genre_1 _/a>,
<a href="genre/2">title_genre_2 _/a>
Movie: <a href="movie/2 (id_movie)">title_movie_2 _/a>
Genre:
<a href="genre/1">title_genre_1 _/a>,
<a href="genre/3">title_genre_3 _/a>
Movie: <a href="movie/3 (id_movie)">title_movie_3 _/a>
Genre:
<a href="genre/1">title_genre_1 _/a>
<a href="genre/2">title_genre_2 _/a>
<a href="genre/3">title_genre_3 _/a>
我找不到... 请帮忙!我在等!
真诚的,Areku
答案 0 :(得分:2)
SELECT
T1.movie_id,
T1.movie_title,
T2.genre_id,
T2.genre_title
FROM
Table3 AS T3
INNER JOIN Table1 AS T1 ON T3.movie_id = T1.movie_id
INNER JOIN Table2 AS T2 ON T3.genre_1 = T2.genre_id
ORDER BY
T1.movie_id
这将返回类似的内容:
movie_id | movie_title | genre_id | genre_title
1 | title_movie_1 | 1 | title_genre_1
1 | title_movie_1 | 2 | title_genre_2
2 | title_movie_2 | 1 | title_genre_1
2 | title_movie_2 | 3 | title_genre_3
3 | title_movie_3 | 1 | title_genre_1
3 | title_movie_3 | 3 | title_genre_3
3 | title_movie_3 | 2 | title_genre_2
之后,您可以循环浏览所有记录;如果movie_id发生了变化,则打印movie_title,然后打印genre_title。
$currentMovie = 0;
while ($row = mysql_fetch_row($result))
{
if($row['movie_id'] != $current_movie)
{
$currentMovie = $row['movie_id'];
echo "Movie: <a href=\"movie/" + $row['movie_id'] + "\">" + $row['movie_title'] + "</a><br />Genre:<br />"
}
echo "<a href=\"genre/" + $row['genre_id'] + "\">" + $row['genre_id'] + "</a><br />"
}
答案 1 :(得分:1)
执行多对多SQL查询:
SELECT m.movie_id, m.movie_title, g.genre_id, g.genre_title
FROM movies m
INNER JOIN movie_genres mg ON m.movie_id = mg.movie_id
INNER JOIN genres g ON g.genre_id = mg.genre_id
然后按电影ID循环结果和分组。