DBMS/MySql (MariaDB)
MySQL/정규식 검색
건담아빠
2022. 9. 19. 09:52
temp table rows
WITH t_temp AS (
SELECT '1' AS test_type, '가나다123' AS test_name
UNION ALL
SELECT '1,2,3', '23'
UNION ALL
SELECT '1,3', '12나다4'
UNION ALL
SELECT '1,2,3,4', '32가다123'
UNION ALL
SELECT '1,6', '다123'
UNION ALL
SELECT '2,5,6', '한글만있음'
)
LIKE 검색 레코드
temp_type 필드의 '1'을 포함한 레코드 출력
- 기본
WITH t_temp AS ( ... )
SELECT xxx.*
FROM t_temp AS xxx
WHERE xxx.temp_type LIKE '%1%'
- 정규식
WITH t_temp AS ( ... )
SELECT xxx.*
FROM t_temp AS xxx
WHERE 1 = 1
AND xxx.test_type REGEXP '1'
LIKE OR 검색 레코드
temp_type 필드의 '2', '3', '4' 을(를) 포함한 레코드 출력
- 기본
WITH t_temp AS ( ... )
SELECT xxx.*
FROM t_temp AS xxx
WHERE 1 = 1
AND (
xxx.test_type LIKE '2'
OR
xxx.test_type LIKE '3'
OR
xxx.test_type LIKE '4'
)
- 정규식
WITH t_temp AS ( ... )
SELECT xxx.*
FROM t_temp AS xxx
WHERE 1 = 1
AND xxx.test_type REGEXP '2|3|4'
특정 값 검색 레코드
temp_type 필드의 콤마로 구분된 '2' 또는 '6'을 포함한 레코드 출력 (실제로는 ,2 ,6 등일듯)
- 정규식
WITH t_temp AS ( ... )
SELECT xxx.*
FROM t_temp AS xxx
WHERE 1 = 1
AND CONCAT(',', xxx.test_type, ',') REGEXP ',(2,6),'
한글 값 레코드
temp_type 필드에 한글이 포함된 모든 레코드를 검색
- 정규식
SELECT xxx.*
FROM t_temp AS xxx
WHERE xxx.test_name regexp '[가-힇]'
한글만 있는 레코드
temp_type 필드에 한글이 포함된 모든 레코드를 검색
- 정규식
SELECT xxx.*
FROM t_temp AS xxx
WHERE xxx.test_name regexp '^[가-힇]+$'
기타
정규식 규칙
. : 문자 하나
* : 앞에 나온 문자의 0개 이상 반복
^ : 문자열의 처음
$ : 문자열의 끝
[.] : 괄호 안의 문자열 일치를 확인
{.} : 반복
| : or
php 샘플
정규식으로 사용할때 주의할 점은 SQL Injection 방지를 위해 사전에 정의된 값으로 설정하여야 한다.
/**
* 정규식으로 검색
*
* @param $sField
* @param $mValue
* @param $aMapping
* @param string $sConcatWord
* @return string
*/
protected function regexp($sField, $mValue, $aMapping, $sConcatWord = '')
{
$mValue = is_array($mValue) === false ? [$mValue] : $mValue;
$sRegexp = '(' . implode('|', array_map(function ($mVal) use ($aMapping) {
return empty($aMapping[$mVal]) === false ? $mVal : false;
}, $mValue)) . ')';
if (empty($sConcatWord) === false) {
$sField = sprintf('CONCAT(%s, %s, %s)', $this->helper->escape($sConcatWord), $sField, $this->helper->escape($sConcatWord));
$sRegexp = sprintf('%s%s%s', $sConcatWord, $sRegexp, $sConcatWord);
}
return sprintf('%s REGEXP %s', $sField, $this->helper->escape($sRegexp));
}
$this->regexp('alias.test_type', [1,3,4], [
1 => 'test1',
2 => 'test2',
3 => 'test3',
4 => 'test4',
5 => 'test5',
], ',');
참조)
https://dev.mysql.com/doc/refman/8.0/en/regexp.html
MySQL :: MySQL 8.0 Reference Manual :: 12.8.2 Regular Expressions
12.8.2 Regular Expressions Table 12.14 Regular Expression Functions and Operators Name Description NOT REGEXP Negation of REGEXP REGEXP Whether string matches regular expression REGEXP_INSTR() Starting index of substring matching regular expression REGE
dev.mysql.com