根据 MySQL 中的键值对显示记录
为此,请使用 JSON_OBJECTAGG()。我们首先创建一个表 -
mysql> create table DemoTable ( Id int, FirstName varchar(100), Age int ); Query OK, 0 rows affected (0.56 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable values(10,'John',23); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values(20,'Carol',21); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(10,'Sam',24); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(20,'Chris',20); Query OK, 1 row affected (0.13 sec)
使用 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)
广告