K
K
kealman2016-07-09 13:20:28
MySQL
kealman, 2016-07-09 13:20:28

MySQL. How to aggregate sub-query to JSON?

Is it possible somehow in MySQL to aggregate subqueries in JSON format?
For example, as PgSQL:

SELECT t1.id, json_agg((SELECT * FROM t2 WHERE t2.id = t1.id)) FROM t1;

Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2016-07-09
@qonand

in MySQL, if I'm not mistaken, there is no analogue of json_agg, but you can solve this problem, for example, by concatenation, like this (the request was written on the knee as an example of the direction where to move):

SELECT 
    t1.id, 
    CONCAT('[{',
    GROUP_CONCAT( 
      (SELECT CONCAT('field1: ', t2.field1, ', field2: ' t2.field2) FROM t2 WHERE t2.id = t1.id)  
       SEPARATOR ' }, { '
   ), '}]'
FROM t1 GROUP BY t1.id

PS I do not recommend using nested queries, it is better to use JOIN

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question