根据条件更新不同字段的 MySQL 查询?
首先,我们创建一个 -
mysql> create table DemoTable1436 -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(20) -> ); Query OK, 0 rows affected (1.06 sec)
使用 insert 在表中插入一些记录 -
mysql> insert into DemoTable1436(Name) values('Chris'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable1436(Name) values('David'); Query OK, 1 row affected (0.40 sec) mysql> insert into DemoTable1436(Name) values('Bob'); Query OK, 1 row affected (0.35 sec) mysql> insert into DemoTable1436(Name) values('David'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable1436(Name) values('David'); Query OK, 1 row affected (0.31 sec)
使用 select 显示表中的所有记录 -
mysql> select * from DemoTable1436;
这将生成以下输出 -
+----+-------+ | Id | Name | +----+-------+ | 1 | Chris | | 2 | David | | 3 | Bob | | 4 | David | | 5 | David | +----+-------+ 5 rows in set (0.00 sec)
以下是对不同字段进行基于条件更新的查询 -
mysql> update DemoTable1436 -> set Name=IF(Name='David','Carol Taylor',Name) -> where Id=2; Query OK, 1 row affected (0.31 sec) Rows matched: 1 Changed: 1 Warnings: 0
让我们再次查看表记录 -
mysql> select * from DemoTable1436;
这将生成以下输出 -
+----+--------------+ | Id | Name | +----+--------------+ | 1 | Chris | | 2 | Carol Taylor | | 3 | Bob | | 4 | David | | 5 | David | +----+--------------+ 5 rows in set (0.00 sec)
广告