A
A
Andrey Surzhikov2017-05-01 17:38:08
MySQL
Andrey Surzhikov, 2017-05-01 17:38:08

How to join from another table as a JSON array?

Good afternoon!
The new mysql 5.7 has functions for working with JSON.
Could you tell me if it is possible to make such a request and if so, how?
Two tables: users (users) and payments (payments), related payments.user_id. You need to display the users table so that a column containing the JSON array of user payments is added to the right.
users

-----------
| id | name |
 -----------
|  1 | Иван |
 -----------
|  2 | Петр |
 -----------

payments
------------------------------
| id | user_id | summ | status |
 ------------------------------
|  1 |       1 |  100 |      1 |
 ------------------------------
|  2 |       1 |  200 |      0 |
 ------------------------------
|  3 |       1 |  100 |      0 |
 ------------------------------
|  4 |       1 |  140 |      1 |
 ------------------------------
|  5 |       2 |  300 |      1 |
 ------------------------------
|  6 |       2 |  500 |      0 |
 ------------------------------

users_with_payments
------------------------------------------------
| id | name | payments_json                      |
 ------------------------------------------------
|  1 | Иван | [{"id":1, "summ":100, "status":1}, |
|    |      | {"id":2, "summ":200, "status":0},  |
|    |      | {"id":3, "summ":100, "status":0},  |
|    |      | {"id":4, "summ":140, "status":1}]  |
 ------------------------------------------------
|  2 | Петр | [{"id":5, "summ":300, "status":1}  |
|    |      | {"id":6, "summ":500, "status":0}]  |
 ------------------------------------------------

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2017-05-01
@Surzhikov

select
  u.*,
  group_concat(json_object('id', p.id, 'summ', p.summ, 'status', p.status)) as payments_json
from user as u
inner join payments as p
  on u.id = p.user_id
group by u.id, u.name;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question