How to JOIN 2 tables in MYSQL with same ID on mult

2019-09-09 14:12发布

I'm having a hard time figuring this out. Hope someone can help me figure this out.


For example. I have a video site and in this video site I can submit video posts with the name of people who play in this video. But I don't want to add just 1 name it can be more. So i'd have a video.php page and in this page I can submit the video title of the video and the names of people who play in it.

table: post

    -------------------------------------------
  -- video_id ---- video_name ----  video_cast -- 
    -------------------------------------------
       1              Vid-1           1
       2              Vid-2           2
       3              Vid-2           2   

table: cast

    -----------------------------------------
  -- cast_id ----  cast_name ----  cast_video -- 
    -----------------------------------------
       1              John            1
       2              Erik            2
       3              Ela             2

Now if i would be on my homepage and I see this new post. If I click on it. It will send the video_id information in the header so I can fetch it from the video.php.

page: video.php

<?php   

    $id = $_GET['id'];
    $result = mysql_query
    ("
        SELECT * 
        FROM post 
        LEFT JOIN cast 
        ON post.video_cast = cast.cast_video
        WHERE video_id='$id' 
    ");

    while($row = mysql_fetch_array($result)){
        echo ' 
                   <h1>'.$row['video_name'].'</h1> 
                   starring: '.$row['cast_name'].
                 ';                   
    }
?>

Now how would I be able to show the video_name and all the cast_name that are associated with the video. The JOIN code I use can only show 1 name out of the table. Anybody know how I could fetch the other remaining name(s)?

标签: php mysql join row
1条回答
Deceive 欺骗
2楼-- · 2019-09-09 14:40

You can list the names in one row with group_concat()

 SELECT video_name, group_concat(cast_name) cast
 FROM post 
 LEFT JOIN cast ON post.video_cast = cast.cast_video
 WHERE video_id='$id' 
 group by video_name
查看更多
登录 后发表回答