Mysql將查詢結果集轉換為JSON數據的實例代碼

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數據內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!