이를 위해 CASE 문을 사용하고 조건을 설정하여 임시 열에 결과를 얻을 수 있습니다.
먼저 테이블을 생성하겠습니다 -
mysql> create table DemoTable ( EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY, EmployeeName varchar(20), EmployeeSalary int, EmployeeExperience int ); Query OK, 0 rows affected (0.64 sec)
다음은 삽입 명령을 사용하여 테이블에 일부 레코드를 삽입하는 쿼리입니다 -
mysql> insert into DemoTable(EmployeeName,EmployeeSalary,EmployeeExperience) values('Larry',4500,5); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable(EmployeeName,EmployeeSalary,EmployeeExperience) values('Mike',130000,8); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable(EmployeeName,EmployeeSalary,EmployeeExperience) values('Sam',11000,5); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(EmployeeName,EmployeeSalary,EmployeeExperience) values('Carol',140000,8) ; Query OK, 1 row affected (0.18 sec)
다음은 select 명령 -
을 사용하여 테이블의 레코드를 표시하는 쿼리입니다.mysql> select *from DemoTable;
이것은 다음과 같은 출력을 생성합니다 -
+------------+--------------+----------------+--------------------+ | EmployeeId | EmployeeName | EmployeeSalary | EmployeeExperience | +------------+--------------+----------------+--------------------+ | 1 | Larry | 4500 | 5 | | 2 | Mike | 130000 | 8 | | 3 | Sam | 11000 | 5 | | 4 | Carol | 140000 | 8 | +------------+--------------+----------------+--------------------+ 4 rows in set (0.00 sec)
다음은 값이 다른 열에 의존하는 MySQL에서 임시 열을 추가하는 쿼리입니다. 여기서 임시 열은 NewSalary −
입니다.mysql> select EmployeeId,EmployeeName,EmployeeSalary,EmployeeExperience, case when EmployeeExperience=5 then EmployeeSalary+10000 when EmployeeExperience=8 then EmployeeSalary+20000 else null end as NewSalary from DemoTable;
이것은 다음과 같은 출력을 생성합니다 -
+------------+--------------+----------------+--------------------+-----------+ | EmployeeId | EmployeeName | EmployeeSalary | EmployeeExperience | NewSalary | +------------+--------------+----------------+--------------------+-----------+ | 1 | Larry | 4500 | 5 | 14500 | | 2 | Mike | 130000 | 8 | 150000 | | 3 | Sam | 11000 | 5 | 21000 | | 4 | Carol | 140000 | 8 | 160000 | +------------+--------------+----------------+--------------------+-----------+ 4 rows in set (0.00 sec)