在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Mysql将查询结果集转换为JSON数据 前言学生表学生成绩表查询单个学生各科成绩(转换为对象JSON串并用逗号拼接)将单个学生各科成绩转换为数组JSON串将数组串作为value并设置key两张表联合查询(最终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"}] 最终结果
到此这篇关于Mysql将查询结果集转换为JSON数据的文章就介绍到这了,更多相关mysql结果集转换json数据内容请搜索极客世界以前的文章或继续浏览下面的相关文章希望大家以后多多支持极客世界! |
请发表评论