一、group_concat函數的功能
將group by產生的同一個分組中的值連接起來,返回一個字符串結果。
group_concat函數首先根據group by指定的列進行分組,將同一組的列顯示出來,並且用分隔符分隔。由函數參數(字段名)決定要返回的列。例如:
create table emp( emp_id int primary key auto_increment comment '編號', emp_name char(20) not null default '' comment '姓名', salary decimal(10,2) not null default 0 comment '工資', department char(20) not null default '' comment '部門' ); insert into emp(emp_name,salary,department) values('張晶晶',5000,'財務部'),('王飛飛',5800,'財務部'),('趙剛',6200,'財務部'),('劉小貝',5700,'人事部'), ('王大鵬',6700,'人事部'),('張小斐',5200,'人事部'),('劉雲雲',7500,'銷售部'),('劉雲鵬',7200,'銷售部'), ('劉雲鵬',7800,'銷售部');
執行如下查詢及結果:
select group_concat(emp_name) from emp; +----------------------------------------------------------------------------------------+
| group_concat(emp_name) |
+----------------------------------------------------------------------------------------+
| 張晶晶,王飛飛,趙剛,劉小貝,王大鵬,張小斐,劉雲雲,劉雲鵬,劉雲鵬 |
+----------------------------------------------------------------------------------------+
1 row in set (0.00 sec) mysql> select department,group_concat(emp_name) from emp group by department; +------------+-------------------------------+
| department | group_concat(emp_name) |
+------------+-------------------------------+
| 人事部 | 劉小貝,王大鵬,張小斐 |
| 財務部 | 張晶晶,王飛飛,趙剛 |
| 銷售部 | 劉雲雲,劉雲鵬,劉雲鵬 |
+------------+-------------------------------+
3 rows in set (0.00 sec)
二、函數語法:
group_concat( [DISTINCT] 要連接的字段 [Order BY 排序字段 ASC/DESC] [Separator ‘分隔符’] )
group_concat([distinct] 字段名 [order by 排序字段 asc/desc] [separator '分隔符'])
說明:
(1)使用distinct可以排除重復值;
(2)如果需要對結果中的值進行排序,可以使用order by子句;
(3)separator是一個字符串值,默認為逗號。
下面舉例說明:select id,price from goods;
以id分組,把price字段的值在同一行打印出來,逗號分隔(默認):select id, group_concat(price) from goods group by id;
以id分組,把price字段的值在一行打印出來,分號分隔:select id,group_concat(price separator ';') from goods group by id;
以id分組,把去除重復冗余的price字段的值打印在一行,逗號分隔:select id,group_concat(distinct price) from goods group by id;
以id分組,把price字段的值去重打印在一行,逗號分隔,按照price倒序排列:select id,group_concat(DISTINCT price order by price desc) from goods group by id;
三、示例代碼
select t1.foodId, t2.name, sum(t1.foodNum) as foodsNum, GROUP_CONCAT(t3.orderCode order by t3.orderCode desc SEPARATOR ',') orderlist from foods_order t1, foods_info t2, order_info t3 where t1.orderId = t3.id and t1.foodId = t2.id and t3.createTime >= '2020-11-07 00:00:00' and t3.createTime <= '2020-11-07 18:30:00' and t3.orderState in ('2','3','4','5') group by t1.foodId, t2.name
其中2個方法:sum():取某字段的總數;group_concat:就是上面介紹的用法