我們已經(jīng)知道m(xù)ysql使用sql select命令和where子句來(lái)讀取數(shù)據(jù)表中的數(shù)據(jù),但是當(dāng)提供的查詢(xún)條件字段為null時(shí),該命令可能就無(wú)法正常工作。
為了處理這種情況時(shí),MySQL提供了三大運(yùn)算符:
IS NULL:當(dāng)列的值為NULL,此運(yùn)算符返回true。
IS NOT NULL:當(dāng)列的值不為NULL,運(yùn)算符返回true。
:??比較操作符(不同于=運(yùn)算符),當(dāng)比較的的兩個(gè)值為NULL時(shí)返回真。
關(guān)于NULL的條件比較運(yùn)算是比較特殊的。你不能使用= NULL或!= NULL在列中查找NULL值。
在MySQL中,NULL值與任何其它值的比較(即使是NULL)永遠(yuǎn)返回false,即NULL = NULL返回false。
MySQL中處理NULL使用IS NULL和IS NOT NULL運(yùn)算符。
在命令提示符中使用NULL值
以下實(shí)例中假設(shè)數(shù)據(jù)庫(kù)指南中的表tcount_tbl包含兩列tutorial_author和tutorial_count,tutorial_count中設(shè)置插入NULL值。
嘗試以下實(shí)例:
root?@?host#mysql?-u?root?-p?password; 輸入密碼:******* mysql>?use?TUTORIALS;數(shù)據(jù)庫(kù)已更改mysql>?create?table?tcount_tbl ????-?>( ????-?>?tutorial_author?varchar(40)NOT?NULL, ????-?>?tutorial_count?INT ????-?>); 查詢(xún)OK,0行受影響(0.05秒) mysql>?INSERT?INTO?tcount_tbl ????-?>(tutorial_author,tutorial_count)值('mahran',20); mysql>?INSERT?INTO?tcount_tbl ????-?>(tutorial_author,tutorial_count)values('mahnaz',NULL); mysql>?INSERT?INTO?tcount_tbl ????-?>(tutorial_author,tutorial_count)值('Jen',NULL); mysql>?INSERT?INTO?tcount_tbl ????-?>(tutorial_author,tutorial_count)值('Gill',20); mysql>?select?*?from?tcount_tbl; +?-----------------?+?----------------?+ |?tutorial_author?|?tutorial_count?| +?-----------------?+?----------------?+ |?馬赫蘭?20?| |?mahnaz?|?NULL?| |?仁|?NULL?| |?鰓|?20?| +?-----------------?+?----------------?+ 4行(0.00秒) MySQL的>
以下實(shí)例中你可以看到=和!=運(yùn)算符是不起作用的
mysql>?SELECT?*?FROM?tcount_tbl?WHERE?tutorial_count?=?NULL; 空置(0.00秒) mysql>?SELECT?*?FROM?tcount_tbl?WHERE?tutorial_count!=?NULL; 空置(0.01秒)
查詢(xún)數(shù)據(jù)表中tutorial_count列是否為NULL,必須使用IS NULL和IS NOT NULL,如下實(shí)例:
mysql>?SELECT?*?FROM?tcount_tbl? ????-?>?WHERE?tutorial_count?IS?NULL; +?-----------------?+?----------------?+ |?tutorial_author?|?tutorial_count?| +?-----------------?+?----------------?+ |?mahnaz?|?NULL?| |?仁|?NULL?| +?-----------------?+?----------------?+ 2行(0.00秒) mysql>?select?*?from?tcount_tbl? ????-?>?WHERE?tutorial_count?is?NOT?NULL; +?-----------------?+?----------------?+ |?tutorial_author?|?tutorial_count?| +?-----------------?+?----------------?+ |?馬赫蘭?20?| |?鰓|?20?| +?-----------------?+?----------------?+ 2行(0.00秒)
使用PHP腳本處理NULL值
PHP腳本中你可以在MySQL … MySQL語(yǔ)句來(lái)處理MySQL是否為空,并生成相應(yīng)的條件語(yǔ)句。
以下實(shí)例中PHP設(shè)置了$ tutorial_count變量,然后使用該變量與數(shù)據(jù)表中的tutorial_count字段進(jìn)行比較:
”。 ?????????“Count:{$?row?['tutorial_count']}?<br>”。 ?????????“--------------------------------結(jié)果”; }? echo“成功獲取數(shù)據(jù)?n”; mysql_close($康恩); ?>
【相關(guān)推薦】
1.?特別推薦:MySQL