假设我有一张表 mytable :
select * from mytable
:
+------+------+------+
| a | b | c |
+------+------+------+
| 1 | 1 | a |
| 1 | 2 | b |
+------+------+------+
我想将 b 和 c 列与group_concat
函数分组:
select a, group_concat(b), group_concat(c) from mytable group by a
+------+-----------------+-----------------+
| a | group_concat(b) | group_concat(c) |
+------+-----------------+-----------------+
| 1 | 1,2 | a,b |
+------+-----------------+-----------------+
我的问题是,做mysql保证,group_concat
将始终保持相同的顺序,我将不会得到第二列 1,2 的结果和 b,第三栏中的?
答案 0 :(得分:5)
您可以在GROUP_CONCAT
函数中使用ORDER BY
子句:
SELECT a,
GROUP_CONCAT(b ORDER BY b),
GROUP_CONCAT(c ORDER BY c)
FROM mytable GROUP BY a
答案 1 :(得分:4)
如果没有指定order by
订单,则无法保证订单,group_concat()
拥有订单order by clause
的原因相同。根据MySQL Spec,语法如下
GROUP_CONCAT([DISTINCT] expr [,expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name ...]]
[SEPARATOR str_val])
因此,如果您想确定订单,请指定order by
之类的
select a,
group_concat(b order by b desc) as b_concat,
group_concat(c order by c desc) as c_concat
from mytable
group by a