我需要查询4个表中的数据。我不确定这是解决此问题的最佳数据库设计。这是简化版。实际的表有更多的列。我有上传他们的歌曲的用户的表:
Id | Username |
---------------
1 | John |
2 | Michael |
3 | Frank |
然后我有这样的歌曲表
Id | Title | UserId
----------------------
1 | Title 1 | 1
2 | Title 2 | 1
3 | Title 3 | 2
4 | Title 4 | 2
然后是这样的播放列表
Id | Title | UserId
------------------------
1 | My Playlist | 3
然后,用户保存歌曲ID的播放列表条目属于播放列表
Id | SongId | PlaylistId
--------------------------
1 | 2 | 1
2 | 4 | 1
3 | 3 | 1
查询后我想要达到的目的是:
Playlist | By | Song List
------------------------------------------------------------
My Playlist | Frank | Title 2 - John, Title 3 - Michael,
| | Title 4 - Michael
-------------------------------------------------------------
任何想法如何在MySQL中查询。或者任何更好的桌面设计,以达到理智的结果?
答案 0 :(得分:0)
试试这个:
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