对于条件,请在MySQL中使用CASE语句。让我们首先创建一个表-
mysql> create table DemoTable1545 -> ( -> Id int, -> FirstName varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1545 values(1,'John'); mysql> insert into DemoTable1545 values(2,'Chris'); mysql> insert into DemoTable1545 values(3,'Bob');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1545;
这将产生以下输出-
+------+-----------+ | Id | FirstName | +------+-----------+ | 1 | John | | 2 | Chris | | 3 | Bob | +------+-----------+ 3 rows in set (0.00 sec)
这是使用CASE语句设置不同ID的查询-
mysql> update DemoTable1545 -> set Id= -> case when FirstName like '%John%' then 101 -> when FirstName like '%Chris%' then 201 -> when FirstName like '%Bob%' then 501 -> else Id -> end; Rows matched: 3 Changed: 3 Warnings: 0
让我们再次检查表记录-
mysql> select * from DemoTable1545;
这将产生以下输出-
+------+-----------+ | Id | FirstName | +------+-----------+ | 101 | John | | 201 | Chris | | 501 | Bob | +------+-----------+ 3 rows in set (0.00 sec)