MySQL NULL 值处理实例详解
MySQLNULL值处理
我们已经知道MySQL使用SQLSELECT命令及WHERE子句来读取数据表中的数据,但是当提供的查询条件字段为NULL时,该命令可能就无法正常工作。
为了处理这种情况,MySQL提供了三大运算符:
- ISNULL:当列的值是NULL,此运算符返回true。
- ISNOTNULL:当列的值不为NULL,运算符返回true。
- <=>:比较操作符(不同于=运算符),当比较的的两个值为NULL时返回true。
关于NULL的条件比较运算是比较特殊的。你不能使用=NULL或!=NULL在列中查找NULL值。
在MySQL中,NULL值与任何其它值的比较(即使是NULL)永远返回false,即NULL=NULL返回false。
MySQL中处理NULL使用ISNULL和ISNOTNULL运算符。
在命令提示符中使用NULL值
以下实例中假设数据库TUTORIALS中的表tcount_tbl含有两列tutorial_author和tutorial_count,tutorial_count中设置插入NULL值。
实例
尝试以下实例:
root@host#mysql-uroot-ppassword;
Enterpassword:*******
mysql>useTUTORIALS;
Databasechanged
mysql>createtabletcount_tbl
->(
->tutorial_authorvarchar(40)NOTNULL,
->tutorial_countINT
->);
QueryOK,0rowsaffected(0.05sec)
mysql>INSERTINTOtcount_tbl
->(tutorial_author,tutorial_count)values('mahran',20);
mysql>INSERTINTOtcount_tbl
->(tutorial_author,tutorial_count)values('mahnaz',NULL);
mysql>INSERTINTOtcount_tbl
->(tutorial_author,tutorial_count)values('Jen',NULL);
mysql>INSERTINTOtcount_tbl
->(tutorial_author,tutorial_count)values('Gill',20);
mysql>SELECT*fromtcount_tbl;
+-----------------+----------------+
|tutorial_author|tutorial_count|
+-----------------+----------------+
|mahran|20|
|mahnaz|NULL|
|Jen|NULL|
|Gill|20|
+-----------------+----------------+
4rowsinset(0.00sec)
mysql>
以下实例中你可以看到=和!=运算符是不起作用的:
mysql>SELECT*FROMtcount_tblWHEREtutorial_count=NULL; Emptyset(0.00sec) mysql>SELECT*FROMtcount_tblWHEREtutorial_count!=NULL; Emptyset(0.01sec)
查找数据表中tutorial_count列是否为NULL,必须使用ISNULL和ISNOTNULL,如下实例:
mysql>SELECT*FROMtcount_tbl ->WHEREtutorial_countISNULL; +-----------------+----------------+ |tutorial_author|tutorial_count| +-----------------+----------------+ |mahnaz|NULL| |Jen|NULL| +-----------------+----------------+ 2rowsinset(0.00sec) mysql>SELECT*fromtcount_tbl ->WHEREtutorial_countISNOTNULL; +-----------------+----------------+ |tutorial_author|tutorial_count| +-----------------+----------------+ |mahran|20| |Gill|20| +-----------------+----------------+ 2rowsinset(0.00sec)
使用PHP脚本处理NULL值
PHP脚本中你可以在if...else语句来处理变量是否为空,并生成相应的条件语句。
以下实例中PHP设置了$tutorial_count变量,然后使用该变量与数据表中的tutorial_count字段进行比较:
<?php
$dbhost='localhost:3036';
$dbuser='root';
$dbpass='rootpassword';
$conn=mysql_connect($dbhost,$dbuser,$dbpass);
if(!$conn)
{
die('Couldnotconnect:'.mysql_error());
}
if(isset($tutorial_count))
{
$sql='SELECTtutorial_author,tutorial_count
FROMtcount_tbl
WHEREtutorial_count=$tutorial_count';
}
else
{
$sql='SELECTtutorial_author,tutorial_count
FROMtcount_tbl
WHEREtutorial_countIS$tutorial_count';
}
mysql_select_db('TUTORIALS');
$retval=mysql_query($sql,$conn);
if(!$retval)
{
die('Couldnotgetdata:'.mysql_error());
}
while($row=mysql_fetch_array($retval,MYSQL_ASSOC))
{
echo"Author:{$row['tutorial_author']}<br>".
"Count:{$row['tutorial_count']}<br>".
"--------------------------------<br>";
}
echo"Fetcheddatasuccessfully\n";
mysql_close($conn);
?>
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!