3

我有一个相当大的查询要从每个国家/地区提取有关报告的信息,而现在,我可以限制它的唯一方法是Limit 10在末尾放置或一些数字,这将限制国家/地区。但是,我想要做的是将group_concat每个国家/地区的结果限制为 10 个,在我的情况下,这会以某种方式将每个单词的实例限制为 10 个group_concat

我目前的查询是:

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 中,因为您只能根据字符进行限制。以前有人解决过这个问题吗?

4

2 回答 2

2

解决方法
一种选择是用空格#填充您的值。所以 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

于 2011-05-24T20:09:17.220 回答
2

这是我限制每个用户的帖子的示例之一

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;
于 2012-11-27T13:55:55.200 回答