简体   繁体   中英

How to JOIN 2 tables in MYSQL with same ID on multiple rows

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)?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM