본문 바로가기
Back-End/Database, SQL

[MySQL] JSON_ARRAYAGG로 JSON 데이터 출력하기

by developerDoorold 2023. 2. 14.

MySQL의 JSON_ARRAYAGG 함수는 SQL 쿼리에서 JSON 배열을 생성할 때 사용할 수 있습니다.

 

용례는 다음과 같습니다.

SELECT JSON_ARRAYAGG(column_name)
FROM table_name;

위 쿼리는 'table_name' 테이블에서 'column_name' 컬럼의 값을 JSON 배열로 묶어 리턴합니다.

 

예시)

CREATE TABLE fruits (
  name VARCHAR(20)
);

INSERT INTO fruits (name) VALUES
  ('apple'),
  ('banana'),
  ('cherry');

SELECT JSON_ARRAYAGG(name)
FROM fruits;  // [  "apple",  "banana",  "cherry"]

 

내가 사용한 쿼리

SELECT
    ur.uuid,
    JSON_ARRAYAGG(st.name) AS shop_type
FROM user_reservation ur
         INNER JOIN shop s ON s.uuid = ur.shop_uuid
         INNER JOIN user_reservation_shop_type urst ON ur.uuid = urst.user_rez_uuid
         LEFT JOIN shop_type st ON st.uuid = urst.shop_type_uuid
WHERE ur.user_uuid = 'uuid'
GROUP BY ur.uuid

댓글