MySQL null的一些易错点
依据null-values,MySQL的值为null的意思只是代表没有数据,null值和某种类型的零值是两码事,比如int类型的零值为0,字符串的零值为””,但是它们依然是有数据的,不是null.
我们在保存数据的时候,习惯性的把暂时没有的数据记为null,表示当前我们无法提供有效的信息.
不过使用null但是时候,需要我们注意一些问题.对此MySQL文档说明如下:problems-with-null
使用null的易错点
下面我摘取MySQL官方给出的null的易错点做讲解.
对MySQL不熟悉的人很容易搞混null和零值
TheconceptoftheNULLvalueisacommonsourceofconfusionfornewcomerstoSQL
比如下面这2句SQL产生的数据是独立的
mysql>INSERTINTOmy_table(phone)VALUES(NULL); mysql>INSERTINTOmy_table(phone)VALUES('');
第一句SQL只是表示暂时不知道电话号码是多少,第二句是电话号码知道并且记录为''
Bothstatementsinsertavalueintothephonecolumn,butthefirstinsertsaNULLvalueandthesecondinsertsanemptystring.Themeaningofthefirstcanberegardedas“phonenumberisnotknown”andthemeaningofthesecondcanberegardedas“thepersonisknowntohavenophone,andthusnophonenumber.”
对null的逻辑判断要单独处理
对于是否为null的判断必须使用专门的语法ISNULL,ISNOTNULL,IFNULL().
TohelpwithNULLhandling,youcanusetheISNULLandISNOTNULLoperatorsandtheIFNULL()function.
如果你使用=判断,那么永远是false
InSQL,theNULLvalueisnevertrueincomparisontoanyothervalue,evenNULL
TosearchforcolumnvaluesthatareNULL,youcannotuseanexpr=NULLtest.Thefollowingstatementreturnsnorows,becauseexpr=NULLisnevertrue
比如你这样写,where后判断的结果永不会是true:
SELECT*FROMmy_tableWHEREphone=NULL;
如果你使用null和其他数据做计算,那么结果永远是null,除非MySQL文档对某些操作做了额外的特殊说明
AnexpressionthatcontainsNULLalwaysproducesaNULLvalueunlessotherwiseindicatedinthedocumentationfortheoperatorsandfunctionsinvolvedintheexpression
例如:
mysql>SELECTNULL,1+NULL,CONCAT('Invisible',NULL); +------+--------+--------------------------+ |NULL|1+NULL|CONCAT('Invisible',NULL)| +------+--------+--------------------------+ |NULL|NULL|NULL| +------+--------+--------------------------+ 1rowinset(0.00sec)
所以你要对null做逻辑判断,还是乖乖的使用ISNULL
TolookforNULLvalues,youmustusetheISNULLtest
对有null值的列做索引要额外预料到隐藏的细节
只有InnoDB,MyISAM,MEMORY存储引擎支持给带有null值的列做索引
YoucanaddanindexonacolumnthatcanhaveNULLvaluesifyouareusingtheMyISAM,InnoDB,orMEMORYstorageengine.Otherwise,youmustdeclareanindexedcolumnNOTNULL,andyoucannotinsertNULLintothecolumn.
索引的长度会比普通索引大1,也就是略微耗内存点
Duetothekeystorageformat,thekeylengthisonegreaterforacolumnthatcanbeNULLthanforaNOTNULLcolumn.
对null值做分组,去重,排序会被特殊对待
和上文讲的=null永远是false相反,这时null被认为是相等的.
WhenusingDISTINCT,GROUPBY,orORDERBY,allNULLvaluesareregardedasequal.
对null排序会被特殊对待
null值要么被排在最前面,要么最后面
WhenusingORDERBY,NULLvaluesarepresentedfirst,orlastifyouspecifyDESCtosortindescendingorder.
聚合操作时null被忽略
Aggregate(group)functionssuchasCOUNT(),MIN(),andSUM()ignoreNULLvalues
例如count(*)不会统计值为null的数据.
TheexceptiontothisisCOUNT(*),whichcountsrowsandnotindividualcolumnvalues.Forexample,thefollowingstatementproducestwocounts.Thefirstisacountofthenumberofrowsinthetable,andthesecondisacountofthenumberofnon-NULLvaluesintheagecolumn:
mysql>SELECTCOUNT(*),COUNT(age)FROMperson;
以上就是MySQLnull的一些易错点的详细内容,更多关于MySQLnull的资料请关注毛票票其它相关文章!