mysql列转行函数是什么

2022-07-01 11:01:17 IT技术网 互联网
浏览

在mysql中,列转行函数是“group_concat()”函数;该函数用于将非空列值按照分组条件进行合并并最终返回,如果其中有空值则返回的结果是空,语法为“select group_concat(name separator ';')列名 from 表名;”。

本教程操作环境:windows10系统、mysql8.0.22版本、Dell G3电脑。

mysql列转行函数是什么

GROUP_CONCAT(expr)该函数将非空列值按照分组条件进行合并并最终返回。如果有空值,则返回为空

在MySQL中,如何将列转成一行?比如一个一个商品会属于多个分类(如华为手机可以是手机分类,也可以是数码分类),如何将此商品在一条数据中展现所有分类。

思路很简单,通过MySQL函数group_concat即可解决。

创建测试表:

create table test.test_mysql_liezhuanhang (
id         bigint auto_increment comment '主键',
name       varchar(100),
age        int(5),
primary key (id)
)engine=innodb default charset=utf8mb4 comment='测试表'

导入测试数据:

insert into test.test_mysql_liezhuanhang (name, age) values ('李威', 18), ('李威', 19), ('李威', 18), ('李白', 20), ('李白', 20), ('李白', 19);

展现所有名字,以分号分割,默认以,分割

select group_concat(name  separator ';') concat
  from test.test_mysql_liezhuanhang 
;

01.png

展现所有名字,并将相同名字去重

select group_concat(distinct name) concat
  from test.test_mysql_liezhuanhang 
;

02.png

展现所有年龄,去重并以年龄升序排序

select group_concat(distinct age order by age) concat
  from test.test_mysql_liezhuanhang 
;

03.png

推荐学习:mysql视频教程

以上就是mysql列转行函数是什么的详细内容,更多请关注dnjidi.com其它相关文章!