JSON ARRAY 합치기


//-------------------------------------
* JSON 배열  합치기만
    - JSON_ARRAYAGG  이용
    - JSON_TABLE 을 사용하지 않으면 
        - "[1,2]" , "[2,3]"  를 합치면 => "[[1,2], [2,3]]" 으로 결과가 나옴
        - 원하는 결과는 "[1,2,2,3]"


SET @json = '["a", "b", "b", "a", "c"]';

SELECT  JSON_ARRAYAGG( item ) )
FROM JSON_TABLE( @json, '$[*]'
    COLUMNS(     item TEXT PATH '$'    )
) as items
ORDER BY items.item;  # 정렬



//-------------------------------------
* JSON 배열 합치고 중복값 제거(unique, distinct)
    - JSON_OBJECTAGG   와 JSON_KEYS 이용
    - 주의!  JSON_KEYS 의 결과의 각 요소는 문자열 형태

SET @json = '["a", "b", "b", "a", "c"]';

SELECT JSON_KEYSJSON_OBJECTAGG( item, "" ) )
FROM JSON_TABLE( @json, '$[*]' 
    COLUMNS(    item TEXT PATH '$'   )
) as items;



//-------------------------------------
https://stackoverflow.com/questions/58051995/how-to-get-unique-distinct-elements-inside-json-array-in-mysql-5-7
https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html
https://dev.mysql.com/doc/refman/8.0/en/json-function-reference.html


반응형
Posted by codens