Mysql将查询结果集转换为JSON数据的实例代码
程序员文章站
2022-08-17 20:29:17
mysql将查询结果集转换为json数据 前言学生表学生成绩表查询单个学生各科成绩(转换为对象json串并用逗号拼接)将单个学生各科成绩转换为数组json串将数组串作为value并设置key两张表联合...
mysql将查询结果集转换为json数据 前言学生表学生成绩表查询单个学生各科成绩(转换为对象json串并用逗号拼接)将单个学生各科成绩转换为数组json串将数组串作为value并设置key两张表联合查询(最终sql,每个学生各科成绩)最终结果
前言
我们经常会有这样一种需求,一对关联关系表,一对多的关系,使用一条sql语句查询两张表的所有记录,例:一张学生表,一张学生各科成绩表,我们想要用一条sql查询出每个学生各科成绩;
学生表
create table if not exists `student`( `id` int unsigned auto_increment, `name` varchar(100) not null primary key ( `id` ) )engine=innodb default charset=utf8; insert into student( id, name ) values ( 1, '张三' ); insert into student( id, name ) values ( 2, '李四' );
学生成绩表
create table if not exists `score`( `id` int unsigned auto_increment, `name` varchar(100) not null `student_id` int(100) not null, `score` varchar(100) not null primary key ( `id` ) )engine=innodb default charset=utf8; insert into score( id, name, student_id, score) values ( 1, '数学', 1, '95.5' ); insert into score( id, name, student_id, score) values ( 2, '语文', 1, '99.5' ); insert into score( id, name, student_id, score) values ( 3, '数学', 2, '95.5' ); insert into score( id, name, student_id, score) values ( 4, '语文', 2, '88' );
查询单个学生各科成绩(转换为对象json串并用逗号拼接)
select group_concat(json_object( 'id',id,'name',name,'student_id',student_id, 'score', score)) as scores from scroe where student_id = 1; ## 查询结果 ## {"id": 1, "name": "数学", "student_id": 1, "score": "95.5"},{"id": 2, "name": "语文", "student_id": 1, "score": "99.5"}
将单个学生各科成绩转换为数组json串
select concat('[', group_concat(json_object( 'id',id,'name',name,'student_id',student_id, 'score', score)), ']') as scores from scroe where student_id = 1 ## 查询结果 ## [{"id": 1, "name": "数学", "student_id": 1, "score": "95.5"},{"id": 2, "name": "语文", "student_id": 1, "score": "99.5"}]
将数组串作为value并设置key
select concat('{"scoredata":[', group_concat(json_object( 'id',id,'name',name,'student_id',student_id, 'score', score)), ']}') as scores from scroe where student_id = 1 ## 查询结果 ## {"scoredata": [{"id": 1, "name": "数学", "student_id": 1, "score": "95.5"},{"id": 2, "name": "语文", "student_id": 1, "score": "99.5"}]}
两张表联合查询(最终sql,每个学生各科成绩)
select id, name, (select concat('[', group_concat(json_object( 'id',id,'name',name,'student_id',student_id, 'score', score)), ']') as scores from scroe where student_id = stu.id) as scores from student stu ## [{"id": 1, "name": "数学", "student_id": 1, "score": "95.5"},{"id": 2, "name": "语文", "student_id": 1, "score": "99.5"}]
最终结果
id | name | scores |
---|---|---|
1 | 张三 | [{“id”: 1, “name”: “数学”, “student_id”: 1, “score”: “95.5”},{“id”: 2, “name”: “语文”, “student_id”: 1, “score”: “99.5”}] |
2 | 李四 | [{“id”: 3, “name”: “数学”, “student_id”: 1, “score”: “95.5”},{“id”:4, “name”: “语文”, “student_id”: 1, “score”: “88”}] |
到此这篇关于mysql将查询结果集转换为json数据的文章就介绍到这了,更多相关mysql结果集转换json数据内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!