其他分享
首页 > 其他分享> > 有人发现(一种简单的方法)限制group_concat行吗?

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

作者:互联网

我有一个很大的查询要从每个国家/地区提取有关报告的信息,现在,我唯一可以限制此范围的方法是在末尾添加限制10或某个数字,这将限制国家/地区.但是,我想做的是将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

标签:concat,concatenation,group-concat,mysql,php
来源: https://codeday.me/bug/20191102/1992583.html