0

每个人,

我只是好奇是否有办法通过对 mySQL 数据库的查询来进行这种限制:

这是我的表:

Events
   event_id   event_title   creation_time

Images
   image_id   src   event_id

Comments
   event_comment_id   event_comment   event_id

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

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

4

1 回答 1

1

这是一种方法。基本上,获取与每组评论/图像关联的行号,最多只显示 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

于 2013-02-16T23:49:55.383 回答