duanbi1983 2018-12-19 06:45
浏览 56

ManyToMany关系连接三个表,限制mysql中第三个表的第三个表限制的结果

I have three tables that are in ManyToMany relationship. 1.playlist 2.tracks 3.playlist_tracks

I want to retrieve 10 playlist with limit of 5 songs. how can i do it? I have tried with this way..

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 ;

but don't get proper result, as it is not applying limit on tracks. It returns all the songs of particular playlist. Where I am doing wrong> Please help me.Here is the DBfiddle for the same sqlfiddle.com/#!9/feddbd/1

  • 写回答

1条回答 默认 最新

  • dqlk31541 2018-12-19 12:18
    关注

    Try this for limiting 5 songs for each playlist_track :

    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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器