ITPub博客

首页 > 数据库 > MySQL > MySQL update ...set后的and写法的逻辑

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

原创 MySQL 作者:哎呀我的天呐 时间:2022-08-04 16:55:36 0 删除 编辑

正常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


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29990276/viewspace-2909051/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
https://cloud.tencent.com/developer/inventory/14362

注册时间:2014-10-30

  • 博文量
    403
  • 访问量
    2528861