解决方法
一个选项是垫你的价值观与
空间
#
。因此,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
的帖子我认为你必须做一个“每组前N个”查询和应用GROUP_CONCAT其结果。 – 2011-05-24 19:36:31
哇,这可能是很多额外的代码来编写。会惹一下它。 – 2011-05-24 19:40:19
Gah ...不要使用重复的字符串连接。使查询难以阅读。使用heredoc(php.net/heredoc),这样你就可以拥有一些PHP所包围的“纯粹”sql。 – 2011-05-24 19:49:57