[gorm] mysql json 구조 쿼리 및 JSON_OVERLAPS
golang , mysql, gorm 환경에서 json 필드를 사용해서 데이터를 관리하려함
원하는건
where 여러 조건 and ( 요일 in ( '월', 화, 수 )
이런 느낌으로 셀렉하고 싶었으나... 문제가 좀 많았다.
문제 1
mysql, mariaDB 가 json 쿼리 함수가 다르다.
마리아DB는
SELECT JSON_CONTAINS(@json, '2', '$.A');
이런 식이고, mysql은 파라미터가 2개만 들어감
https://stackoverflow.com/questions/43247098/mysql-filter-json-contains-any-value-from-array
MySQL Filter JSON_CONTAINS Any value from Array
I have a JSON field in a MySQL database that contains values like [1,3,4,7]. I would like to be able to easily supply another array from a PHP variable and determine if there is any overlap. I know
stackoverflow.com
mysql 쿼리
문제2
요일 in (월, 화, 수)
이런 기능을 json으로 하고 싶었는데...
마리아 DB기준 json_overlaps 이 함수다
https://mariadb.com/kb/en/json_overlaps/
JSON_OVERLAPS
Returns true if two json documents have at least one key-value pair or array element in common.
mariadb.com
문젠, 이게 .. 버전을 탄다.
mariaDB 10.9 부터 가능
나는 10.6 이라서.. 쓸수가없다..
문제3
json_overlaps 이걸 쓰지 못해서
JSON_CONTAINS 를 연결해야했따
where A ~~~~~ 조건 and ( JSON_CONTAINS or JSON_CONTAINS or JSON_CONTAINS )
이런 식으로 ...
근데... gorm 에서는 ( 괄호를 사용하기 힘들다
DB().Where -> and
DB().Or -> or
조건인데... 괄호를 구현하기가 힘들다
그래서 ... string으로 raw쿼리로 짜야했다.,.
// 요일 검색
condition := ""
for _, day := range req.Data.Days {
condition += fmt.Sprintf("JSON_CONTAINS(data, '%s', '$.days') OR ", day)
}
// 마지막 OR 제거
condition = strings.TrimSuffix(condition, " OR ")
base.Where(condition)
이런 느낌으로 ...
아무래도 ... 방법이 없다.