有没有人发现一种限制group_concat行的(简单)方法?

| 我有一个很大的查询要从每个国家/地区提取有关报告的信息,现在,我可以限制这一点的唯一方法是在末尾加上ѭ0或某个数字,这将限制国家/地区。但是,我想做的是将每个国家/地区的
group_concat
限制为10个结果,在我的情况下,将以某种方式将
group_concat
的每个实例限制为10个。 我当前的查询是:
SELECT country,
GROUP_CONCAT(docID),
GROUP_CONCAT(analyst),
GROUP_CONCAT(region),
GROUP_CONCAT(report),
GROUP_CONCAT(topic),
MAX((date)) AS date,
MAX((docID)) AS docID,
GROUP_CONCAT(date) AS dates,
GROUP_CONCAT(event) AS events,
GROUP_CONCAT(province) AS provinces
FROM reports GROUP BY country 
ORDER BY date DESC, docID DESC
我已经看到这个问题,也没有看到任何真正好的答案。我知道该函数未内置在MySQL中,因为您只能基于字符进行限制。有人解决过这个问题吗?     
已邀请:
解决方法 一种选择是用空格
#
填充您的值。因此,group_concat中的每个项目都具有相同的长度。 假设没有超过20个字符的项目。 那么您的查询将是:
SET group_concat_max_len = 10*20+9; /*execute this first.*/
/*10 items, 20 bytes each + 9 bytes for the separator*/

SELECT country,
REPLACE(GROUP_CONCAT(RIGHT(CONCAT(repeat(\'#\',20),docID),20)),\'#\',\'\') AS docIDs, 
REPLACE(GROUP_CONCAT(RIGHT(CONCAT(repeat(\'#\',20),analyst),20)),\'#\',\'\') AS analysts, 
REPLACE(GROUP_CONCAT(RIGHT(CONCAT(repeat(\'#\',20),region,20)),\'#\',\'\') AS regions, 
REPLACE(GROUP_CONCAT(RIGHT(CONCAT(repeat(\'#\',20),report,20)),\'#\',\'\') AS reports, 
REPLACE(GROUP_CONCAT(RIGHT(CONCAT(repeat(\'#\',20),topic,20)),\'#\',\'\') AS topics, 
MAX((date)) AS `date`,  /* LATEST DATE*/
MAX((docID)) AS docID,  /* LATEST DOC*/
REPLACE(GROUP_CONCAT(RIGHT(CONCAT(repeat(\'#\',20),date,20)),\'#\',\'\') AS dates, 
REPLACE(GROUP_CONCAT(RIGHT(CONCAT(repeat(\'#\',20),event,20)),\'#\',\'\') AS events, 
REPLACE(GROUP_CONCAT(RIGHT(CONCAT(repeat(\'#\',20),province,20)),\'#\',\'\') AS provinces 
FROM reports 
GROUP BY country ORDER BY `date` DESC, docID DESC
总结一下:
x= CONCAT(repeat(\'#\',20),docID)  adds 20 x #################### in front of docID
y= RIGHT(X,20)                   Takes the rightmost 20 chars of that
z= GROUP_CONCAT(y)               strings these together up to max_len
result = REPLACE(z,\'#\',\'\') removes the `#` so the result looks normal.
或编写您自己的group_concat版本 您可以使用自己的group_concat UDF。 网上有几个例子。 例如:http://www.codeproject.com/KB/database/mygroupconcat.aspx?display=Mobile     
这是我限制每位用户发帖的示例之一
select user_id,SUBSTRING_INDEX(group_concat(posts.id order by rand()),\',\',3) from posts inner join users on users.id = posts.user_id group by posts.user_id;
    

要回复问题请先登录注册