MySQL에서는 SELECT IF 문에 OR 연산자를 함께 사용할 수 있습니다. IF 문은 조건이 참일 때와 거짓일 때 각각 다른 값을 반환하는 조건부 함수로, OR 연산자를 결합하면 여러 조건 중 하나라도 만족하는 경우를 처리할 수 있습니다.
1. 예제 테이블 생성
먼저 실습을 위해 직원 정보를 저장할 테이블을 생성하겠습니다. 테이블 생성 쿼리는 다음과 같습니다.
mysql> create table EmployeeInformation
-> (
-> EmployeeId int,
-> EmployeeName varchar(100),
-> EmployeeStatus varchar(100)
-> );
Query OK, 0 rows affected (0.68 sec)
2. 샘플 데이터 삽입
INSERT 명령을 사용해 테이블에 직원 레코드를 추가합니다. 각 직원은 FullTime(정규직), PartTime(시간제), Intern(인턴) 중 하나의 상태를 가집니다.
mysql> insert into EmployeeInformation values(1,'Sam','FullTime');
Query OK, 1 row affected (0.23 sec)
mysql> insert into EmployeeInformation values(2,'Mike','PartTime');
Query OK, 1 row affected (0.14 sec)
mysql> insert into EmployeeInformation values(3,'Bob','Intern');
Query OK, 1 row affected (0.14 sec)
mysql> insert into EmployeeInformation values(4,'Carol','FullTime');
Query OK, 1 row affected (0.16 sec)
mysql> insert into EmployeeInformation values(5,'John','FullTime');
Query OK, 1 row affected (0.19 sec)
mysql> insert into EmployeeInformation values(6,'Johnson','PartTime');
Query OK, 1 row affected (0.19 sec)
mysql> insert into EmployeeInformation values(7,'Maria','Intern');
Query OK, 1 row affected (0.12 sec)
3. 전체 데이터 조회
SELECT 명령으로 테이블의 모든 레코드를 확인합니다.
mysql> select *from EmployeeInformation;
출력 결과
+------------+--------------+----------------+
| EmployeeId | EmployeeName | EmployeeStatus |
+------------+--------------+----------------+
| 1 | Sam | FullTime |
| 2 | Mike | PartTime |
| 3 | Bob | Intern |
| 4 | Carol | FullTime |
| 5 | John | FullTime |
| 6 | Johnson | PartTime |
| 7 | Maria | Intern |
+------------+--------------+----------------+
7 rows in set (0.00 sec)
4. OR 조건이 포함된 SELECT IF 문 실행
이제 핵심인 OR 연산자가 포함된 SELECT IF 문을 살펴보겠습니다. 아래 쿼리는 직원 상태(EmployeeStatus)가 'FullTime' 또는 'Intern'인 경우에는 직원 이름(EmployeeName)을 반환하고, 그 외의 경우(예: PartTime)에는 해당 직원의 상태 값을 그대로 반환합니다.
mysql> select if(EmployeeStatus='FullTime' or
EmployeeStatus='Intern',EmployeeName,EmployeeStatus) as Status from
EmployeeInformation;
출력 결과
+----------+
| Status |
+----------+
| Sam |
| PartTime |
| Bob |
| Carol |
| John |
| PartTime |
| Maria |
+----------+
7 rows in set (0.00 sec)
결과 분석
출력 결과를 보면 로직이 명확하게 동작한 것을 확인할 수 있습니다.
Sam, Bob, Carol, John, Maria는 상태가 'FullTime' 또는 'Intern'이므로 IF 조건이 참이 되어 직원 이름이 반환되었습니다. 반면 Mike와 Johnson은 상태가 'PartTime'으로 두 조건 모두 해당하지 않기 때문에 조건이 거짓이 되어 'PartTime'이라는 상태 값이 그대로 출력되었습니다.
이처럼 IF 문 내에서 OR 연산자를 사용하면 하나의 쿼리로 여러 조건을 유연하게 처리할 수 있으며, CASE 문을 간단하게 대체하는 용도로도 활용할 수 있습니다.