如何使用MySQL更新特定列中除单个值以外的所有条目?
要在忽略单个值的同时更新所有条目,需要使用IF()。
让我们首先创建一个表-
create table DemoTable736 ( CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY, CustomerName varchar(100), isMarried boolean );
使用插入命令在表中插入一些记录-
insert into DemoTable736(CustomerName,isMarried) values('Chris',0); insert into DemoTable736(CustomerName,isMarried) values('Robert',0); insert into DemoTable736(CustomerName,isMarried) values('David',0); insert into DemoTable736(CustomerName,isMarried) values('Mike',0); insert into DemoTable736(CustomerName,isMarried) values('Carol',1); insert into DemoTable736(CustomerName,isMarried) values('Bob',0);
使用select语句显示表中的所有记录-
select *from DemoTable736;
这将产生以下输出-
+------------+--------------+-----------+ | CustomerId | CustomerName | isMarried | +------------+--------------+-----------+ | 1 | Chris | 0 | | 2 | Robert | 0 | | 3 | David | 0 | | 4 | Mike | 0 | | 5 | Carol | 1 | | 6 | Bob | 0 | +------------+--------------+-----------+ 6 rows in set (0.00 sec)
以下是使用MySQL更新除特定列中的单个值以外的所有条目的查询。在这里,我们正在更新“isMarried”列-
update DemoTable736 set isMarried=if(CustomerId=5,1,1); Rows matched: 6 Changed: 5 Warnings: 0
让我们再次检查表记录-
select *from DemoTable736;
这将产生以下输出-
+------------+--------------+-----------+ | CustomerId | CustomerName | isMarried | +------------+--------------+-----------+ | 1 | Chris | 1 | | 2 | Robert | 1 | | 3 | David | 1 | | 4 | Mike | 1 | | 5 | Carol | 1 | | 6 | Bob | 1 | +------------+--------------+-----------+ 6 rows in set (0.00 sec)