在MySQL中添加一个临时列,其中值取决于另一列?

您可以为此使用CASE语句并设置条件以在临时列中获取结果。

让我们首先创建一个表-

mysql> create table DemoTable
   (
   EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   EmployeeName varchar(20),
   EmployeeSalary int,
   EmployeeExperience int
   );

以下是使用insert命令在表中插入一些记录的查询-

mysql> insert into DemoTable(EmployeeName,EmployeeSalary,EmployeeExperience) values('Larry',4500,5);
mysql> insert into DemoTable(EmployeeName,EmployeeSalary,EmployeeExperience) values('Mike',130000,8);
mysql> insert into DemoTable(EmployeeName,EmployeeSalary,EmployeeExperience) values('Sam',11000,5);
mysql> insert into DemoTable(EmployeeName,EmployeeSalary,EmployeeExperience) values('Carol',140000,8) ;

以下是查询以使用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)