MySQL NULL 值處理實例教程

MySQL MySQL值處理

我們已經(jīng)知道m(xù)ysql使用sql select命令和where子句來讀取數(shù)據(jù)表中的數(shù)據(jù),但是當(dāng)提供的查詢條件字段為null時,該命令可能就無法正常工作。

為了處理這種情況時,MySQL提供了三大運算符:

IS NULL:當(dāng)列的值為NULL,此運算符返回true。

IS NOT NULL:當(dāng)列的值不為NULL,運算符返回true。

:??比較操作符(不同于=運算符),當(dāng)比較的的兩個值為NULL時返回真。

關(guān)于NULL的條件比較運算是比較特殊的。你不能使用= NULL或!= NULL在列中查找NULL值。

在MySQL中,NULL值與任何其它值的比較(即使是NULL)永遠返回false,即NULL = NULL返回false。

MySQL中處理NULL使用IS NULL和IS NOT NULL運算符。

在命令提示符中使用NULL值

以下實例中假設(shè)數(shù)據(jù)庫指南中的表tcount_tbl包含兩列tutorial_author和tutorial_count,tutorial_count中設(shè)置插入NULL值。

嘗試以下實例:

root?@?host#mysql?-u?root?-p?password;  輸入密碼:*******  mysql>?use?TUTORIALS;數(shù)據(jù)庫已更改mysql>?create?table?tcount_tbl  ????-?>(  ????-?>?tutorial_author?varchar(40)NOT?NULL,  ????-?>?tutorial_count?INT  ????-?>);  查詢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的>

以下實例中你可以看到=和!=運算符是不起作用的

mysql>?SELECT?*?FROM?tcount_tbl?WHERE?tutorial_count?=?NULL;  空置(0.00秒)  mysql>?SELECT?*?FROM?tcount_tbl?WHERE?tutorial_count!=?NULL;  空置(0.01秒)

查詢數(shù)據(jù)表中tutorial_count列是否為NULL,必須使用IS NULL和IS NOT NULL,如下實例:

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腳本中你可以在MySQLMySQL語句來處理MySQL是否為空,并生成相應(yīng)的條件語句。

以下實例中PHP設(shè)置了$ tutorial_count變量,然后使用該變量與數(shù)據(jù)表中的tutorial_count字段進行比較:

”。  ?????????“Count:{$?row?['tutorial_count']}?<br>”。  ?????????“--------------------------------結(jié)果”;  }?  echo“成功獲取數(shù)據(jù)?n”;  mysql_close($康恩);  ?&gt;

【相關(guān)推薦】

1.?特別推薦MySQL

2.MySQLMySQL

3.?MySQLMySQL

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點贊6 分享