MYSQL 하나의 속성에 여러가지의 속성이 붙을때

최정환·2022년 4월 6일
0
 select p.name, c.name as category, price, sizes.size from products as p join categories as c on category_id=c.id join product_size as ps on ps.product_id=p.id join sizes on ps.size_id=sizes.id where c.name="러그" group by p.name, price, size;

name이 각각 다른 price와 size를 가지고 있다.

price만 가지고 있다면 그냥 price에 JSON_ARRAYAGG 이용해 묶어줄 수 있지만 속성이 두가지라 어려웠다.


price 하나만 묶었을 경우

JSON_ARRAYAGG안에 두 가지(size, price)를 넣는다면 문법 오류가 난다.



사이즈에 따른 가격이라 size와 price는 함께 묶여있어도 괜찮기 때문에 값들을 키와 값으로 만들어주는 JSON_OBJECT를 사용하기로 했다.

JSON_OBJECT(key, value)
// 결과
{key:value}

이러면 하나의 결과값으로 나오기 때문에 JSON_ARRAYAGG를 통해 묶어 줄 수 있었다.

select p.name, JSON_ARRAYAGG(JSON_OBJECT(size,price)) as prices from product_size join sizes on size_id=sizes.id join products as p on p.id=product_id join categories as c on c.id=p.category_id where c.name='러그' group by product_id;

prisma를 통해 보내는 json의 형태는 다음과 같다.



만약 이렇게 key와 value 처럼 딱 떨어지지 않고 기준점이 되는 속성값이 중복해서 나온다면

JSON_ARRAYAGG 를 두 번 사용하면 된다.

select p.name, JSON_ARRAYAGG(price) as prices, JSON_ARRAYAGG(size) as sizes from product_size join sizes on size_id=sizes.id join products as p on p.id=product_id join categories as c on c.id=p.category_id where c.name='러그' group by p.name

0개의 댓글