ManyToMany关系将三个表连接起来,并在mysql中

时间:2018-12-19 06:45:43

标签: php mysql laravel

我有3个处于ManyToMany关系的表。 1.播放列表 2.曲目 3.playlist_tracks

我想检索10个播放列表,最多5首歌曲。我该怎么做? 我已经尝试过这种方式。

select t1.id as playlistId, t2.playlist_id as pivot_playlist_id, t2.track_id as track_id 
from playlist t1 
join playlist_tracks t2 on t1.id = t2.playlist_id
left join (
    select t3.id as track_id , t3.is_published 
    from tracks t3
    where t3.is_published = 1 
    group by t3.id limit 5
    ) xx on t2.track_id = xx.track_id 
where t1.prior != 0 AND t1.is_published = 1 ;

但是没有得到正确的结果,因为它没有对音轨施加限制。它返回特定播放列表中的所有歌曲。我在哪里做错了>请帮助我。这里是DBfiddle sqlfiddle.com/#!9/feddbd/1

1 个答案:

答案 0 :(得分:0)

尝试此操作以限制每个播放列表音轨的5首歌曲:

SET @playlist_id=-1;
SELECT * FROM
(
  SELECT track_id,
@row_number:=CASE
    WHEN @playlist_id= playlist_id THEN @row_number + 1
    ELSE 1
END AS track_number,
@playlist_id:=playlist_id as playlist_id
FROM playlist_tracks
ORDER BY playlist_id
) X WHERE track_number<=5