为此,请使用JSON_OBJECTAGG()。让我们首先创建一个表-mysql> create table DemoTable
(
Id int,
FirstName varchar(100),
Age int
);
使用插入命令在表中插入一些记录-mysql> insert into DemoTable values(10,'John',23);
mysql> insert into DemoTable values(20,'Carol',21);
mysql> insert into DemoTable values(10,'Sam',24);
mysql> insert into DemoTable values(20,'Chris',20);
使用select语句显示表中的所有记录-mysql> select *from DemoTable;
这将产生以下输出-+------+-----------+------+
| Id | FirstName | Age |
+------+-----------+------+
| 10 | John | 23 |
| 20 | Carol | 21 |
| 10 | Sam | 24 |
| 20 | Chris | 20 |
+------+-----------+------+
4 rows in set (0.00 sec)
以下是使用MySQL JSON_OBJECT的查询以显示键值对中的记录-mysql> select Id,JSON_OBJECTAGG(FirstName,Age) from DemoTable GROUP BY Id;
这将产生以下输出-+------+-------------------------------+
| Id | JSON_OBJECTAGG(FirstName,Age) |
+------+-------------------------------+
| 10 | {"Sam": 24, "John": 23} |
| 20 | {"Carol": 21, "Chris": 20} |
+------+-------------------------------+
2 rows in set (0.07 sec)