
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Display Records Based on 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)
Advertisements