mySQL - 限制JOIN语句一侧返回的行数?

时间:2013-02-16 23:17:28

标签: mysql

每个人,

我很好奇是否有办法在mySQL数据库上进行这种限制:

以下是我的表格:

Events
   event_id   event_title   creation_time

Images
   image_id   src   event_id

Comments
   event_comment_id   event_comment   event_id

我想获取按创建时间排序的事件,每个事件只能获得3张图片和3条评论。

欢迎任何帮助,资源或批评。谢谢

1 个答案:

答案 0 :(得分:1)

这是一种方法。基本上,获取与每组评论/图像相关联的rownumber,并且最多只显示3:

SELECT E.*, 
  MAX(CASE WHEN I.rn = 1 THEN I.Image_Id END) Image1, 
  MAX(CASE WHEN I.rn = 2 THEN I.Image_Id END) Image2, 
  MAX(CASE WHEN I.rn = 3 THEN I.Image_Id END) Image3, 
  MAX(CASE WHEN C.rn = 1 THEN C.event_comment_id END) Comment1, 
  MAX(CASE WHEN C.rn = 2 THEN C.event_comment_id END) Comment2, 
  MAX(CASE WHEN C.rn = 3 THEN C.event_comment_id END) Comment3
FROM Events E
   LEFT JOIN (SELECT @curRow:=IF(@prevRow = event_id, @curRow + 1, 1) rn,
           Image_Id, src, event_id, @prevRow:= event_id
         FROM Images
           JOIN    (SELECT @curRow := 0) r
         ) I ON E.event_id = I.Event_id
   LEFT JOIN (SELECT @curRow2:=IF(@prevRow2 = event_id, @curRow2 + 1, 1) rn,
           event_comment_id, event_comment, event_id, @prevRow2:= event_id
         FROM Comments
           JOIN    (SELECT @curRow2 := 0) r
         ) C ON E.event_id = C.Event_id 
GROUP BY E.Event_Id
ORDER BY E.Event_Id, E.creation_time DESC

这是SQL Fiddle