限制GROUP_CONCAT()或INNER JOIN的结果

时间:2012-04-17 13:02:45

标签: mysql inner-join greatest-n-per-group group-concat

我已经广泛地阅读了其他关于group_concat()和内部联接的限制的线程,但是没有找到我的答案,所以我想我会继续问它:

我正在开发一个现有的照片社区网站。我想检索在某一天(今天)过生日的会员,然后检索每个会员的5张评价最高的照片。但我也只想要10个“最喜欢的”生日会员(即最喜欢的人数)。这就是我所拥有的:

SELECT users.user_id, users.user_name, 
       GROUP_CONCAT(CONVERT(photos.photo_id,char(32)) 
                    ORDER BY photos.average_rate) as photo_ids
FROM users 
INNER JOIN photos ON photos.user_id=users.user_id
WHERE users.day_of_birth = DATE_FORMAT('2012-04-17', '%m-%d') 
  AND users.photo_count>0 
GROUP BY users.user_id
ORDER BY users.favorite_count DESC, users.photo_count DESC LIMIT 0,10

这就是我想要的,除了我不能将photo_id的数量限制为5.这是一个问题,因为输出将作为JSON发送到应用程序,并且一些成员已经上传了20,000以上照片已经存在,导致输出字符串长得令人无法接受。似乎对我有用的唯一“解决方案”是将服务器变量group_concat_max_len设置为合理的,至少可以容纳5个ID,但这非常hacky且不可靠。有没有办法通过单个查询返回每个用户5 photo_id个?或者我需要在我的PHP中进行循环吗?

我不一定需要以逗号分隔值的photo_id,我也可以完全抛弃group_concat()方法,如果更可行则进行内连接。但即使在那里,我也没有意识到将结果限制为5的方法。

2 个答案:

答案 0 :(得分:1)

这些先进的东西让我爱上了MySQL :)。

SELECT user_id, user_name, 
    GROUP_CONCAT(CONVERT(photo_id, char(32)) ORDER BY photos.average_rate) as photo_ids
FROM (  SELECT user_id, user_name, photo_id, favorite_count, photo_count, 
            (case when @user_id = user_id then @rownum := @rownum + 1 else CONCAT(@rownum := 1, @user_id := user_id) end) AS dummy_val
        FROM (  SELECT users.user_id, users.user_name, users.favorite_count, users.photo_count, photos.photo_id
                FROM users 
                INNER JOIN photos
                ON photos.user_id=users.user_id
                WHERE users.day_of_birth = DATE_FORMAT('2012-04-17', '%m-%d') 
                    AND users.photo_count > 0 
                ORDER BY users.id ASC, photos.average_rate ASC
             ) AS h, 
             (  @rownum := NULL, 
                @user_id := NULL
             ) AS vars
        HAVING rownum <= 5) AS h2
GROUP BY user_id
ORDER BY favorite_count DESC, photo_count DESC LIMIT 0, 10

基本上我得到所有行,并丢弃所有计算出的rownum中6或更高的照片。

答案 1 :(得分:0)

SELECT u.user_id
     , u.user_name 
     , GROUP_CONCAT(p.photo_id ORDER BY p.average_rate) AS photo_ids
FROM 
    ( SELECT user_id
           , user_name
           , favorite_count 
           , photo_count
      FROM users
      WHERE day_of_birth = DATE_FORMAT('2012-04-17', '%m-%d') 
        AND photo_count > 0 
      ORDER BY favorite_count DESC
             , photo_count DESC 
      LIMIT 10
    ) AS u
  INNER JOIN
    photos AS p
      ON  p.user_id = u10.user_id
      AND p.average_rate >= 
          ( SELECT pp.average_rate 
            FROM photos AS pp
            WHERE pp.user_id = u10.user_id
            ORDER BY pp.average_rate DESC
            LIMIT 1 OFFSET 4
          ) 
GROUP BY u.user_id
ORDER BY u.favorite_count DESC
       , u.photo_count DESC