MySQL NULL 值处理实例教程

MySQL MySQL值处理

我们已经知道mysql使用sql select命令和where子句来读取数据表中的数据,但是当提供的查询条件字段为null时,该命令可能就无法正常工作。

为了处理这种情况时,MySQL提供了三大运算符:

IS NULL:当列的值为NULL,此运算符返回true。

IS NOT NULL:当列的值不为NULL,运算符返回true。

:  比较操作符(不同于=运算符),当比较的的两个值为NULL时返回真。

关于NULL的条件比较运算是比较特殊的。你不能使用= NULL或!= NULL在列中查找NULL值。

在MySQL中,NULL值与任何其它值的比较(即使是NULL)永远返回false,即NULL = NULL返回false。

MySQL中处理NULL使用IS NULL和IS NOT NULL运算符。

在命令提示符中使用NULL值

以下实例中假设数据库指南中的表tcount_tbl包含两列tutorial_author和tutorial_count,tutorial_count中设置插入NULL值。

尝试以下实例:

root @ host#mysql -u root -p password;  输入密码:*******  mysql> use TUTORIALS;数据库已更改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秒)

查询数据表中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是否为空,并生成相应的条件语句。

以下实例中PHP设置了$ tutorial_count变量,然后使用该变量与数据表中的tutorial_count字段进行比较:

”。           “Count:{$ row ['tutorial_count']} <br>”。           “--------------------------------结果”;  }   echo“成功获取数据 n”;  mysql_close($康恩);  ?&gt;

【相关推荐】

1. 特别推荐MySQL

2.MySQLMySQL

3. MySQLMySQL

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享