douzao9845 2016-02-28 10:04 采纳率: 0%
浏览 77
已采纳

构造一个MySQL表,其中PLAYLIST表引用多个VIDEO id整数和一个USER表id

I want to retrieve one complete object from VIDEOPLAYLIST that contains the complete USER object and all the VIDEO objects related to it.

I understand that I will need to use LEFT JOIN to merge them, but I cant understand how i should setup my PLAYLIST table and how to query it when it comes to multiple VIDEO id's.

This is my current database EER Diagram: Original EER Diagram of my database tables

Should I create a many to many relationship between the playlist and video? Should I somehow store all the VIDEO id's in the PLAYLIST table? And then how would be able to query it?

This is where I'm stuck:

SELECT * FROM videoplaylist LEFT JOIN user LEFT JOIN video ON user.id = playlist.user_id AND videos....

PS. I won't just be querying one PLAYLIST at the time, as I need to display them in a list format.

  • 写回答

1条回答 默认 最新

  • dpvmjk0479 2016-02-28 10:12
    关注

    Yes, you should create a many-to-many relationship between the video and playlist table if you want that one video could be added to multiple playlists and vice versa.

    So your many-to-many relationship table could look like this where the combination of playlist_id and video_id is your primary key.

    playlist_has_video
    ------------------
    playlist_id
    video_id
    

    If you want to be able to add a video more than once to a playlist you have to create an id col in this table too. So now id is your primary key.

    playlist_has_video
    ------------------
    id
    playlist_id
    video_id
    

    When you want to enable the user to sort the playlist think about adding another col order_id to your n-to-m table.

    playlist_has_video
    ------------------
    id
    playlist_id
    video_id
    order_id
    

    Now lets see the select queries (i will refer to the last design, id + order_id)

    retrieving all videos from a playlist:

    SELECT video.* FROM playlist_has_video AS phv LEFT JOIN video ON phv.video_id = video.id WHERE phv.playlist_id = :playlist_id ORDER BY order_id ASC;
    

    Retrieving all playlists the video is in:

    SELECT playlist.* FROM playlist_has_video AS phv LEFT JOIN playlist ON phv.playlist_id = playlist.id WHERE phv.video_id = :video_id;
    

    You have to alter you video - table too if you use this approach (Make sure you remove playlist_id)

    video
    ---------
    id
    title
    description
    user_id
    transcript_id
    created
    updated
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行