Mysqli 简明教程

MySQLi - Handling NULL Values

我们已经看到了 SQL SELECT 命令以及 WHERE 子句,用于从 MySQL 表中获取数据,但是当我们尝试给出一个条件时,该条件将字段或列值与 NULL 进行比较,它不能正常工作。

We have seen the SQL SELECT command along with the WHERE clause to fetch data from a MySQL table, but when we try to give a condition, which compares the field or the column value to NULL, it does not work properly.

为了处理这种情况,MySQL 提供了三个运算符 -

To handle such a situation, MySQL provides three operators −

  1. IS NULL − This operator returns true, if the column value is NULL.

  2. IS NOT NULL − This operator returns true, if the column value is not NULL.

  3. <⇒ − This operator compares values, which (unlike the = operator) is true even for two NULL values.

涉及 NULL 的条件是特殊的。不能使用 = NULL 或 != NULL 来查找列中的 NULL 值。这种比较始终失败,因为无法判断它们是真还是假。有时,甚至 NULL = NULL 会失败。

The conditions involving NULL are special. You cannot use = NULL or != NULL to look for NULL values in columns. Such comparisons always fail because it is impossible to tell whether they are true or not. Sometimes, even NULL = NULL fails.

要查找存在或不存在 NULL 的列,请使用 IS NULLIS NOT NULL

To look for columns that are or are not NULL, use IS NULL or IS NOT NULL.

Using NULL values at the Command Prompt

假设 TUTORIALS 数据库中有一个名为 tcount_tbl 的表,它包含两列,即 tutorial_authortutorial_count ,其中 tutorial_count 为 NULL 表示该值未知。

Assume that there is a table called tcount_tbl in the TUTORIALS database and it contains two columns namely tutorial_author and tutorial_count, where a NULL tutorial_count indicates that the value is unknown.

Example

尝试以下示例:

Try the following examples −

root@host# mysql -u root -p password;
Enter password:*******

mysql> use TUTORIALS;
Database changed

mysql> create table tcount_tbl
   → (
   → tutorial_author varchar(40) NOT NULL,
   → tutorial_count  INT
   → );
Query OK, 0 rows affected (0.05 sec)

mysql> INSERT INTO tcount_tbl
   → (tutorial_author, tutorial_count) values ('mahran', 20);

mysql> INSERT INTO tcount_tbl
   → (tutorial_author, tutorial_count) values ('mahnaz', NULL);

mysql> INSERT INTO tcount_tbl
   → (tutorial_author, tutorial_count) values ('Jen', NULL);

mysql> INSERT INTO tcount_tbl
   → (tutorial_author, tutorial_count) values ('Gill', 20);

mysql> SELECT * from tcount_tbl;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
|     mahran      |       20       |
|     mahnaz      |      NULL      |
|      Jen        |      NULL      |
|     Gill        |       20       |
+-----------------+----------------+
4 rows in set (0.00 sec)

mysql>

可以看到, = 和 != 不适用于 NULL 值,如下所示:

You can see that = and != do not work with NULL values as follows −

mysql> SELECT * FROM tcount_tbl WHERE tutorial_count = NULL;
Empty set (0.00 sec)

mysql> SELECT * FROM tcount_tbl WHERE tutorial_count != NULL;
Empty set (0.01 sec)

要查找 tutorial_count 列存在或不存在的记录,应按以下程序中所示编写查询。

To find the records where the tutorial_count column is or is not NULL, the queries should be written as shown in the following program.

mysql> SELECT * FROM tcount_tbl
   → WHERE tutorial_count IS NULL;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
|     mahnaz      |      NULL      |
|      Jen        |      NULL      |
+-----------------+----------------+
2 rows in set (0.00 sec)
mysql> SELECT * from tcount_tbl
   → WHERE tutorial_count IS NOT NULL;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
|     mahran      |       20       |
|     Gill        |       20       |
+-----------------+----------------+
2 rows in set (0.00 sec)

Handling NULL Values in a PHP Script

可以使用 if…​else 条件根据 NULL 值准备查询。

You can use the if…​else condition to prepare a query based on the NULL value.

以下示例从外部获取 tutorial_count,然后将其与表中可用值进行比较。

The following example takes the tutorial_count from outside and then compares it with the value available in the table.

Example

将以下示例复制粘贴为 mysql_example.php:

Copy and paste the following example as mysql_example.php −

<html>
   <head>
      <title>Handling NULL</title>
   </head>
   <body>
      <?php
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = 'root@123';
         $dbname = 'TUTORIALS';
         $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
         $tutorial_count = null;
         if($mysqli→connect_errno ) {
            printf("Connect failed: %s<br />", $mysqli→connect_error);
            exit();
         }
         printf('Connected successfully.<br />');

         if( isset($tutorial_count )) {
            $sql = 'SELECT tutorial_author, tutorial_count
               FROM  tcount_tbl
               WHERE tutorial_count = ' + $tutorial_count;
         } else {
            $sql = 'SELECT tutorial_author, tutorial_count
               FROM  tcount_tbl
               WHERE tutorial_count IS NULL';
         }
         $result = $mysqli→query($sql);

         if ($result→num_rows > 0) {
            while($row = $result→fetch_assoc()) {
               printf("Author: %s, Count: %d <br />",
                  $row["tutorial_author"],
                  $row["tutorial_count"]);
            }
         } else {
            printf('No record found.<br />');
         }
         $mysqli→close();
      ?>
   </body>
</html>

Output

访问部署在 Apache Web 服务器上的 mysql_example.php, 并验证输出。

Access the mysql_example.php deployed on apache web server and verify the output.

Connected successfully.
No record found.