MySQL update ...set后的and写法的逻辑

来源:这里教程网 时间:2026-03-01 16:46:59 作者:

正常update语句update table_name set col1=xxx,col2=xxxx,col3=xxxx,col4=xx and col5=xxxx;一眼看上去这个SQL真脑残了,哪个开发写错了写成and,其实不然....这是MySQL中特有的脑残写法... ...真是脑残 二话不说,创建测试表

mysql> create table test1 (expression varchar(100),notes varchar(100));
Query OK, 0 rows affected (0.36 sec)
mysql> insert into test1 values ('5','6');
Query OK, 1 row affected (0.02 sec)
mysql> insert into test1 values ('1121','xxxx');
Query OK, 1 row affected (0.02 sec)
mysql> insert into test1 values ('xxxx','111');
Query OK, 1 row affected (0.01 sec)

执行update set exp1='xxx' and exp2 ='mmm';

mysql> update test1 set expression='5' and notes = '6' ;
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3  Warnings: 0
mysql> select * from test1;
+------------+-------+
| expression | notes |
+------------+-------+
| 1          | 6     |
| 0          | xxxx  |
| 0          | 111   |
+------------+-------+
3 rows in set (0.00 sec)

看到上方的逻辑其实是等价于如下:

mysql> update test1 set expression=(case when notes ='6' then 1 else 0 end);
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3  Warnings: 0
mysql> select * from test1;
+------------+-------+
| expression | notes |
+------------+-------+
| 1          | 6     |
| 0          | xxxx  |
| 0          | 111   |
+------------+-------+
3 rows in set (0.00 sec)

mysql中 and 是当做运算符"&&"  则 set column1=value1 and column2=value2 等价于 set column1=(value1&&column2=value2)即setcolumn1=0或1

相关推荐