在MySQL里面update一条记录,语法都正确的,但记录并没有被更新
有问题的SQL语句:
update apps set owner_code=‘43212’ and owner_name=‘李四’ where owner_code=‘13245’ and owner_name=‘张三’;
执行之前的记录是这样的:
执行之后的记录是这样的:
可以看到,owner_name的值没有变,但owner_code变成了0!
why?
看起来,语法是完全没有问题,翻了翻MySQL官方文档的update语法:
看到assignment_list的格式是以逗号分隔的col_name=value列表,一下子豁然开朗,开发同学想要的多字段更新语句应该这样写:
update apps set owner_code=‘43212’ , owner_name=‘李四’ where owner_code=‘13245’ and owner_name=‘张三’;
倒回去再重试验一把:
果然,这下得到了想要的结果!
原因:
在一条UPDATE语句中,如果要更新多个字段,字段间不能使用“AND”,而应该用逗号分隔。
后记 :回过头来看了一下,为什么使用“AND”分隔的时候,会出现owner_code=0的奇怪结果? 多次尝试之后发现:
update apps set owner_code=‘43212’ and owner_name=‘李四’ where owner_code=‘13245’ and owner_name=‘张三’;
等价于:
update apps set owner_code=(‘43212’ and owner_name=‘李四’) where owner_code=‘13245’ and owner_name=‘张三’;
而 (‘43212’ and owner_name=‘李四’) 是一个逻辑表达式,而这里不难知道owner_name并不是‘李四’。因此,这个逻辑表达式的结果为 false , false在MySQL中等价于0!
以上:有错误请指正。。。