📅  最后修改于: 2020-11-27 06:20:15             🧑  作者: Mango
我们已经看到了SQL SELECT命令和WHERE子句,以便从MySQLi表中获取数据,但是当我们尝试给出一个将字段或列的值与NULL进行比较的条件时,它将无法正常工作。
为了处理这种情况,MySQLi提供了三个运算符
IS NULL-如果列值为NULL ,则运算符返回true。
IS NOT NULL-如果列值不为NULL ,则运算符返回true。
<=> -运算符比较值(与=运算符不同),即使对于两个NULL值也是如此。
涉及NULL的条件是特殊的。您不能使用= NULL或!= NULL在列中查找NULL值。这样的比较总是失败的,因为无法判断它们是否正确。即使NULL = NULL也会失败。
要查找是否为NULL的列,请使用IS NULL或IS NOT NULL。
假设在TUTORIALS数据库中有一个表tutorials_bks ,它包含两列id和name ,其中NULL名称表示该值未知-
尝试以下示例-
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> INSERT INTO tutorials_bks (book) values('');
Query OK, 1 row affected (0.08 sec)
mysql> INSERT INTO tutorials_bks (book) values('');
Query OK, 1 row affected (0.08 sec)
mysql> INSERT INTO tutorials_bks (book) values('');
Query OK, 1 row affected (0.08 sec)
mysql> INSERT INTO tutorials_bks (book) values('NULL');
Query OK, 1 row affected (0.08 sec)
mysql> INSERT INTO tutorials_bks (book) values('NULL');
Query OK, 1 row affected (0.08 sec)
mysql> INSERT INTO tutorials_bks (book) values('NULL');
Query OK, 1 row affected (0.08 sec)
+----+---------+
| id | book |
+----+---------+
| 1 | java |
| 2 | java |
| 3 | html |
| 4 | c++ |
| 5 | Android |
| 6 | |
| 7 | |
| 8 | |
| 9 | NULL |
| 10 | NULL |
| 11 | NULL |
+----+---------+
11 rows in set (0.00 sec)
mysql>
要查找name列为NULL或不为NULL的记录,查询应这样编写:
mysql> SELECT * FROM tutorials_bks WHERE book = "null";
+----+------+
| id | book |
+----+------+
| 9 | NULL |
| 10 | NULL |
| 11 | NULL |
+----+------+
3 rows in set (0.00 sec)
mysql> SELECT * FROM tutorials_bks WHERE book ! = "null";
+----+---------+
| id | book |
+----+---------+
| 1 | java |
| 2 | java |
| 3 | html |
| 4 | c++ |
| 5 | Android |
| 6 | |
| 7 | |
| 8 | |
+----+---------+
8 rows in set (0.00 sec)
mysql> SELECT * FROM tutorials_bks WHERE book = "";
+----+------+
| id | book |
+----+------+
| 6 | |
| 7 | |
| 8 | |
+----+------+
3 rows in set (0.01 sec)
您可以使用if … else条件来准备基于NULL值的查询。
以下示例从外部获取tutorial_count,然后将其与表中的可用值进行比较。
".
"Count: {$row['tutorial_count']}
".
"--------------------------------
";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>