네, MySQL에는 바로 이런 경우를 위해 NOT IN 연산자가 기본으로 제공됩니다. 여러 개의 != 조건을 AND로 연결하는 대신, 제외하고 싶은 값들을 목록으로 한 번에 지정할 수 있어 쿼리가 훨씬 간결해집니다.
NOT IN 연산자의 기본 문법
SELECT * FROM yourTableName WHERE yourColumnName NOT IN (1, 2, 7);
위 문법을 실제로 이해하기 위해 예제 테이블을 만들어 보겠습니다.
예제 테이블 생성하기
먼저 테이블을 생성하는 쿼리는 다음과 같습니다.
mysql> create table User_informations
-> (
-> UserId int,
-> UserName varchar(20)
-> );
Query OK, 0 rows affected (0.47 sec)샘플 데이터 삽입하기
INSERT 명령을 사용해 테이블에 레코드를 몇 개 추가합니다.
mysql> insert into User_informations values(12,'Maxwell'); Query OK, 1 row affected (0.17 sec) mysql> insert into User_informations values(7,'David'); Query OK, 1 row affected (0.10 sec) mysql> insert into User_informations values(1,'Ramit'); Query OK, 1 row affected (0.36 sec) mysql> insert into User_informations values(10,'Bob'); Query OK, 1 row affected (0.19 sec) mysql> insert into User_informations values(2,'Carol'); Query OK, 1 row affected (0.14 sec) mysql> insert into User_informations values(14,'Sam'); Query OK, 1 row affected (0.23 sec) mysql> insert into User_informations values(6,'Mike'); Query OK, 1 row affected (0.12 sec) mysql> insert into User_informations values(4,'Robert'); Query OK, 1 row affected (0.13 sec)
전체 레코드 조회하기
SELECT 문으로 테이블의 모든 레코드를 확인합니다.
mysql> select *from User_informations;
실행 결과는 다음과 같습니다.
+--------+----------+ | UserId | UserName | +--------+----------+ | 12 | Maxwell | | 7 | David | | 1 | Ramit | | 10 | Bob | | 2 | Carol | | 14 | Sam | | 6 | Mike | | 4 | Robert | +--------+----------+ 8 rows in set (0.00 sec)
NOT IN을 활용한 특정 값 제외 조회
이제 질문하신 내용을 NOT IN()으로 구현해 보겠습니다. 아래 쿼리는 UserId가 1, 2, 7인 레코드를 제외한 나머지 행만 반환합니다.
mysql> select *from User_informations where UserId NOT IN(1,2,7);
실행 결과는 다음과 같습니다.
+--------+----------+ | UserId | UserName | +--------+----------+ | 12 | Maxwell | | 10 | Bob | | 14 | Sam | | 6 | Mike | | 4 | Robert | +--------+----------+ 5 rows in set (0.00 sec)
결과에서 확인할 수 있듯이 UserId가 1(Ramit), 2(Carol), 7(David)인 세 개의 레코드가 제외되고 나머지 5개 행만 출력되었습니다. 이처럼 NOT IN을 사용하면 id != 5 AND id != 10 AND id != 15처럼 조건을 일일이 나열하지 않고도 동일한 결과를 훨씬 깔끔하게 얻을 수 있습니다.