You can use CASE statement for this and set conditions to get result in the temporary column.
Let us first create a table −
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)
Following is the query to insert some records in the table using insert command −
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)
Following is the query to display records from the table using select command −
mysql> select *from DemoTable;
This will produce the following output −
+------------+--------------+----------------+--------------------+ | 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)
Following is the query to add a temporary column in MySQL where the values depend on another column. Here the temporary column is 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;
This will produce the following output −
+------------+--------------+----------------+--------------------+-----------+ | 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)