dongzhong5573 2016-07-25 04:04
浏览 24
已采纳

可以组合4个表吗?

I need to query data from 4 tables. I'm not sure this is the best db design to approach this. This is simplified version. The actual table have more column.I have table for users who upload their song:

   Id | Username |
   ---------------
   1  | John     |
   2  | Michael  |
   3  | Frank    |

Then I have song table like this

   Id | Title    | UserId
   ----------------------
   1  | Title 1  | 1
   2  | Title 2  | 1
   3  | Title 3  | 2
   4  | Title 4  | 2

Then a playlist table like this

   Id | Title       | UserId
  ------------------------
   1  | My Playlist | 3

Then a playlist entries where a user save song id belong to a playlist

   Id | SongId  |  PlaylistId
   --------------------------
   1  | 2       | 1
   2  | 4       | 1
   3  | 3       | 1

What I want to achieve after query is something like this:

    Playlist    |  By    |  Song List
   ------------------------------------------------------------
    My Playlist | Frank  |  Title 2 - John, Title 3 - Michael, 
                |        |  Title 4 - Michael
   ------------------------------------------------------------- 

Any idea how to query this in MySQL. Or any better table design to achieve sane result?

  • 写回答

1条回答 默认 最新

  • duancong6937 2016-07-25 04:12
    关注

    Try this:

    SELECT
        p.Title as Playlist,
        u1.Username as By,
        group_concat(s.Title, ' - ', u2.Username order by s.Id) as `Song List`
    FROM playlist p
      JOIN playlist_entries pe
        ON p.Id= pe.PlaylistId
      JOIN song s
        ON pe.SongId = s.Id
      JOIN user u1
        ON p.UserId = u1.Id
      JOIN user u2
        ON s.UserId = u2.Id
    

    <kbd>Demo Here</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请提供一个符合要求的网页链接。
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码