Mysql踩过的坑

数据表示例
1.NOT IN 结果集为空
①SELECT class_no FROM t_student;
结果为:
SELECT * FROM t_student where class_no not in (SELECT class_no FROM t_student);
 
结论:查询语句中not in的结果集中不能有空值,否则查询结果与预期不一致,直接返回空的记录
2.count表达式
①coun(列) 与 count(*)
SELECT COUNT(*) FROM t_student;
结果:5条
 
SELECT COUNT(class_no) FROM t_student;
结果:4条
 
SELECT COUNT(id) FROM t_student;
结果:5条
 
结论:
count(列) : 当列为非空字段时,与count(*)是一样的
当列存在空值时,意义完全不一样
 
②count(列 or NULL)
SELECT COUNT(class_no = '124' or NULL) FROM t_student;
结果:2条
 
SELECT COUNT(class_no = '124') FROM t_student;
结果:3条
结论:因为当 class_no不是124时 class_no='124' 结果false。不是 NULL,
count在值是NULL是不统计数, (count('任意内容')都会统计出所有记录数,因为count只有在遇见null时不计数,即count(null)==0,因此前者单引号内不管输入什么值都会统计出所有记录数),至于加上or NULL , 很像其他编程里的or运算符,第一个表达式是true就是不执行or后面的表达式,第一个表达式是false 执行or后面的表达式 。当class_no不为124时class_no = '124' or NULL 的结果是NULL,Count才不会统计上这条记录数
 
3.update 不能用and
update table set a=xx and b=xxx where ….
更新操作set之后使用and 只会执行a = xx 但是此时不会赋值为xx,而是默认值0(大多数情况字符串1) 情况 但是 mysql并不会报错!!!!!!
 
mysql> select * from test; +------+------+ | c1 | c2 | +------+------+ | 0 | a | +------+------+
他想将c1列的值改成1、c2的值改成'b',然后用了如下sql:
update test set c1=1 and c2='b' where c1=0;
可以发现这个sql写法是错误的,正确写法应该是:
update test set c1=1,c2='b' where c1=0;
但第一个错误的sql运行没报错,因为被MySQL理解成:
update test set c1=(1 and c2='b') where c1=0; => update test set c1=(1 and 0) where c1=0; ==> update test set c1=0 where c1=0;
 
4.待续

猜你喜欢

转载自www.cnblogs.com/cowboys/p/10788116.html