JSON_ARRAYAGG 회고록

5ERN·2023년 1월 8일
0

JavaScript

목록 보기
3/4

이번 1차 프로젝트를 진행 중 장바구니 목록을 가져오는데에 있어서 쿼리문을 두개 작성하여 데이터를 가져와야 하는 상황이 있었다.

이 점에 대해서 JSON_ARRAYAGG를 사용하여 쿼리문 두개를 하나로 줄여쓸 수 있다는 조언을 듣고, 적용시켰으며 그에 대한 회고록을 남긴다.

아래는 내가 작성한 쿼리문이다.

  SELECT
    c.id AS cartId,
    c.quantity AS cartQuantity,
    c.user_id AS cartUserId,
    c.item_id AS cartItemId,
    i.name AS itemsName,
    i.thumbnail AS itemsThumbnail,
    i.price AS itemsPrice,
    JSON_ARRAYAGG(
    JSON_OBJECT(
     "option_id",cartItemOptions.option_id,
     "categoryName",optionCategory.category,
     "content",options.content
     )
     ) AS optionDescription  
  FROM carts c
  INNER JOIN cart_item_options cio ON cartItemOptions.cart_item_id=cart.id
  INNER JOIN options o ON cartItemOptions.option_id=options.id
  INNER JOIN option_categories oc ON options.category_id=optionCategory.id
  INNER JOIN items i ON items.id=cart.item_id
  WHERE cart.user_id=?
  GROUP BY cart.id;

아쉽게도 ARRAYAGG로 묶기 전의 쿼리문 두개는 히스토리에도 남아있지 않아서 가져올 수 없었다...

이렇게 작성했을 경우 carts에 대한 쿼리문과,
options에 대한 쿼리문, 두 쿼리를 엮은 결과가 출력되게 된다.

위의 쿼리를 출력한 결과

위와 같은 결과물을 얻었다!

profile
응애개발자

0개의 댓글