如何在多对多关系中只重复一次行

yzckvree  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(369)

我正在处理php上的多对多关系,我有3个表,movie表包含电影名称,movie id genre表包含流派和流派id,movie\u genre表包含电影id和流派id
类型表具有以下值

(1 ,'action'),
(2 ,'comedy'),
(3 ,'drama'),
(4 ,'mystery');

我使用下面的代码获取数据

$query = " SELECT movie_name,movie_id,genre FROM movies
    JOIN movie_genre ON movies.movie_id = movie_genre.movie_id
    JOIN genre ON movie_genre.genre_id = genre.genre_id
    WHERE movie.movie_id = ?";

    $stmt = mysqli_prepare($conn, $query);
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    if(mysqli_num_rows($result) > 0 ){
    while ($row = mysqli_fetch_assoc($result)) {

    echo ' movie_id: '.$row["movie_id"].' movie name:'.$row["movie_name"].'
    Genres:' .$row["genre"]

        }}

但结果是
电影名称类型[1]
电影名称类型[2]
电影名称类型[3]
一个例子

movie_id:55 movie name: titanic genre : action 

movie_id:55 movie name: titanic genre : drama

movie_id:55 movie name: titanic genre : romance

我想要的结果是

movie_id:55 movie name: titanic genre : action drama romance

我确实尝试使用极限1,但结果只显示了第一种流派

a64a0gku

a64a0gku1#

需要做一个循环,只针对我不能测试的类型,所以这是把我想象的工作,但这将是沿着这些路线的东西,这里可能有语法错误

$query = " SELECT movie_name,movie_id,genre FROM movies
    JOIN movie_genre ON movies.movie_id = movie_genre.movie_id
    JOIN genre ON movie_genre.genre_id = genre.genre_id
    WHERE movie.movie_id = ?";    

    $stmt = mysqli_prepare($conn, $query);
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    if(mysqli_num_rows($result) > 0 ){

    // if it's greater than zero, great, we have at least 1 movie.
    // but if it's greater than 1, then we know we have more than 1 genre

    while ($row = mysqli_fetch_assoc($result)) {
    echo 'movie_id:'.$row["movie_id"].'movie name:'.$row["movie_name"];
    break; // so it only runs through this loop once, instead of using limit
    }//end while

    if(mysqli_num_rows($result) > 1 ){
    // more than 1 genre so loop and print out just genres
    while ($row = mysqli_fetch_assoc($result)) {    
      echo $row["genre"];    
    }//end while
    }//end if more than 1 genre
    }//end if
ghhkc1vu

ghhkc1vu2#

你可以用 GROUP_CONCAT 以及 GROUP BY :

SELECT movie_name,movie_id, GROUP_CONCAT(genre SEPARATOR ' ') AS genre
FROM movies
JOIN movie_genre ON movies.movie_id = movie_genre.movie_id
JOIN genre ON movie_genre.genre_id = genre.genre_id
WHERE movie.movie_id = ?
GROUP BY movie_name,movie_id

相关问题