解決方法
一個選項是墊你的價值觀與
空間
#
。因此,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