table of Contents
1. Grammatical structure
GROUP_CONCAT([DISTINCT] expr [,expr ...] [ORDER BY {unsigned_integer | col_name | expr} [ASC | DESC] [,col_name ...]] [SEPARATOR str_val])
DISTINCT: Use DISTINCT to exclude duplicate values
expr [,expr ...]: one or more fields (or expressions)
ORDER BY {unsigned_integer | col_name | expr} [ASC | DESC] [,col_name ...]: Sort by field or expression, multiple
SEPARATOR str_val: Separator (the default is a comma), you can change the separator to a number by specifying SEPARATOR ";".
You can set a maximum length through the variable group_concat_max_len. The syntax executed at runtime is as follows: SET [SESSION | GLOBAL] group_concat_max_len = unsigned_integer;
If the maximum length is set, the result value is cut to this maximum length. If the grouped characters are too long, you can set the system parameters: SET @@global.group_concat_max_len=40000;
example:
select asin,GROUP_CONCAT(DISTINCT charge) charge,marketplace,department,valid,valid_date from yd_ebay_charge_info_NEW group by asin,marketplace,department,valid,valid_date;
2. Case
Example 1: Query all sub-categories of a category and connect the sub-category IDs with commas
mysql>SELECT GROUP_CONCAT(cat_id) FROM goods_cat WHERE pid = 25;
Example 2: Query all sub-categories of a category and connect the sub-category IDs with semicolons
mysql>SELECT GROUP_CONCAT(cat_id SEPARATOR ';') FROM goods_cat WHERE pid = 25;
Example 3: Query all sub-categories of a category, sort them according to p_order ASC, cat_id DESC and then connect
mysql>SELECT GROUP_CONCAT(cat_id ORDER BY p_order ASC, cat_id DESC) FROM goods_cat WHERE pid = 25;
Example 4: Combined with GROUP BY query
mysql>SELECT pid, GROUP_CONCAT(cat_id) FROM goods_cat GROUP BY pid;
3. Matters needing attention
(1) Maximum length (character) limitation
System variable: group_concat_max_len
SET [SESSION | GLOBAL] group_concat_max_len = val; |
val must be an unsigned integer
With the GROUP_CONCAT function, the LIMIT statement in the SELECT statement has no effect.
(2) INT type trap
When the connected field is of INT type, the lower version or the returned result is not a comma-separated string, but byte[].
At this time, you need to use the CAST or CONVERT function to convert.