上GROUP_CONCAT限制结果()或INNER JOIN(Limit results on an

2019-09-16 14:20发布

我仔细研读大量的其他线程谈论的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被发送到应用程序的问题,以及一些成员上传的向上20000张照片已经,导致不可接受的长输出字符串。 唯一的“解决方案”,似乎对我的工作就是设置服务器变量group_concat_max_len的东西合理,将至少持有5点的ID,但是这是非常哈克和不可靠的。 有没有什么办法来只返回5 photo_id用单查询S每用户? 或将我需要做一个循环,我的PHP?

我不一定需要photo_ids以逗号分隔值,我还可以沟GROUP_CONCAT()完全接近和做内部连接,如果这是更可行的。 但即使在那里,我不知道的方式将结果限制为5。

Answer 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

Basicly我得到的所有行,并扔掉这是6或计算ROWNUM更高的所有照片。



Answer 2:

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 


文章来源: Limit results on an GROUP_CONCAT() or INNER JOIN