首页 文章资讯内容详情

MySQL中不使用临时表更新列数据

2026-06-03 1 花语

为此,请使用CASE语句。即使不使用临时表也可以使用。让我们首先创建一个表-

mysql> create table DemoTable -> ( -> UserName varchar(100), -> UserStatus varchar(100) -> ); Query OK, 0 rows affected (0.74 sec)

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable values(John,Active); Query OK, 1 row affected (0.29 sec) mysql> insert into DemoTable values(Chris,Inactive); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(Bob,Inactive); Query OK, 1 row affected (0.32 sec) mysql> insert into DemoTable values(Robert,Active); Query OK, 1 row affected (0.15 sec)

使用select语句显示表中的所有记录-

mysql> select *from DemoTable;

输出结果

这将产生以下输出-

+----------+------------+ | UserName | UserStatus | +----------+------------+ | John | Active | | Chris | Inactive | | Bob | Inactive | | Robert | Active | +----------+------------+ 4 rows in set (0.00 sec)

以下是使用CASE更新列数据的查询-

mysql> update DemoTable -> set UserStatus=CASE UserStatus WHEN Inactive THEN Active ELSE Inactive END; Query OK, 4 rows affected (0.28 sec) Rows matched: 4 Changed: 4 Warnings: 0

让我们再次检查表记录-

mysql> select *from DemoTable;

输出结果

这将产生以下输出-

+----------+------------+ | UserName | UserStatus | +----------+------------+ | John | Inactive | | Chris | Active | | Bob | Active | | Robert | Inactive | +----------+------------+ 4 rows in set (0.00 sec)