Display records on the basis of key-value pairs in MySQL


For this, use JSON_OBJECTAGG(). Let us first create a table −

mysql> create table DemoTable
(
   Id int,
   FirstName varchar(100),
   Age int
);
Query OK, 0 rows affected (0.56 sec)

Insert some records in the table using insert command −

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)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+-----------+------+
| Id   | FirstName | Age  |
+------+-----------+------+
|   10 | John      |   23 |
|   20 | Carol     |   21 |
|   10 | Sam       |   24 |
|   20 | Chris     |   20 |
+------+-----------+------+
4 rows in set (0.00 sec)

Following is the query using MySQL JSON_OBJECT to display records in key-value pair −

mysql> select Id,JSON_OBJECTAGG(FirstName,Age) from DemoTable GROUP BY Id;

This will produce the following output −

+------+-------------------------------+
| Id   | JSON_OBJECTAGG(FirstName,Age) |
+------+-------------------------------+
|   10 | {"Sam": 24, "John": 23}       |
|   20 | {"Carol": 21, "Chris": 20}    |
+------+-------------------------------+
2 rows in set (0.07 sec)

Updated on: 25-Sep-2019

987 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements