MySQL에서 동적 배열과 함께 LIKE 쿼리를 구현하려면 LIKE 연산자와 ORDER BY, LIMIT 절을 조합하여 사용하면 됩니다. 기본적인 문법은 다음과 같습니다.
기본 문법
select * from yourTableName
where yourColumnName2 like "%yourValue%"
order by yourColumnName1 asc
limit yourLimitValue;
이제 실제 예제를 통해 단계별로 살펴보겠습니다.
1단계: 테이블 생성
먼저 테스트에 사용할 테이블을 생성합니다.
mysql> create table demo74
-> (
-> user_id int not null auto_increment primary key,
-> user_names varchar(250)
-> );
Query OK, 0 rows affected (0.67 sec)
2단계: 데이터 삽입
INSERT 명령을 사용해 샘플 데이터를 입력합니다. 여러 개의 이름이 하나의 문자열에 쉼표로 구분되어 저장되는 경우를 가정합니다.
mysql> insert into demo74(user_names) values("John Smith1,John Smith2,John Smith3");
Query OK, 1 row affected (0.18 sec)
mysql> insert into demo74(user_names) values("John Smith1");
Query OK, 1 row affected (0.15 sec)
mysql> insert into demo74(user_names) values("David Smith1");
Query OK, 1 row affected (0.12 sec)
mysql> insert into demo74(user_names) values("John Smith1,John Smith2,John Smith3,John Smith4");
Query OK, 1 row affected (0.10 sec)3단계: 저장된 데이터 확인
SELECT 문으로 테이블에 저장된 레코드를 조회합니다.
mysql> select *from demo74;
위 쿼리는 다음과 같은 결과를 출력합니다.
출력 결과
+---------+-------------------------------------------------+
| user_id | user_names |
+---------+-------------------------------------------------+
| 1 | John Smith1,John Smith2,John Smith3 |
| 2 | John Smith1 |
| 3 | David Smith1 |
| 4 | John Smith1,John Smith2,John Smith3,John Smith4 |
+---------+-------------------------------------------------+
4단계: LIKE 쿼리로 특정 값 검색
이제 LIKE 연산자를 사용해 "John Smith1"이라는 값을 포함하는 행만 검색합니다. 와일드카드 %를 앞뒤로 붙이면 해당 값이 문자열 어디에 위치하더라도 매칭됩니다.
mysql> select *from demo74
-> where user_names like "%John Smith1%"
-> order by user_id asc
-> limit 100;
위 쿼리는 다음과 같은 결과를 출력합니다.
출력 결과
+---------+-------------------------------------------------+
| user_id | user_names |
+---------+-------------------------------------------------+
| 1 | John Smith1,John Smith2,John Smith3 |
| 2 | John Smith1 |
| 4 | John Smith1,John Smith2,John Smith3,John Smith4 |
+---------+-------------------------------------------------+
3 rows in set (0.00 sec)
결과 분석
위 출력 결과를 보면 "John Smith1"이라는 문자열을 포함하는 3개의 행(user_id 1, 2, 4)만 반환된 것을 확인할 수 있습니다. 반면 "David Smith1"만 저장된 user_id 3번 행은 검색 결과에서 제외되었습니다.
이처럼 %값% 형태의 LIKE 패턴을 사용하면 쉼표로 구분된 여러 값이 저장된 컬럼에서도 원하는 특정 값을 유연하게 검색할 수 있습니다. ORDER BY 절로 정렬 기준을 지정하고, LIMIT 절로 반환할 최대 행 수를 제어할 수 있어 대량의 데이터를 다룰 때도 유용합니다.