3.3.4.6 Working with NULL Values使用NULL值

The NULL value can be surprising until you get used to it. 在您习惯它之前,NULL值可能会令人惊讶。Conceptually, NULL means a missing unknown value and it is treated somewhat differently from other values.从概念上讲,NULL表示“缺少未知值”,它的处理方式与其他值有所不同。

To test for NULL, use the IS NULL and IS NOT NULL operators, as shown here:要测试NULL,请使用IS NULLIS NOT NULL运算符,如下所示:

mysql> SELECT 1 IS NULL, 1 IS NOT NULL;
+-----------+---------------+
| 1 IS NULL | 1 IS NOT NULL |
+-----------+---------------+
|         0 |             1 |
+-----------+---------------+

You cannot use arithmetic comparison operators such as =, <, or <> to test for NULL. 不能使用算术比较运算符,如=<<>测试是否为NULLTo demonstrate this for yourself, try the following query:要亲自演示这一点,请尝试以下查询:

mysql> SELECT 1 = NULL, 1 <> NULL, 1 < NULL, 1 > NULL;
+----------+-----------+----------+----------+
| 1 = NULL | 1 <> NULL | 1 < NULL | 1 > NULL |
+----------+-----------+----------+----------+
|     NULL |      NULL |     NULL |     NULL |
+----------+-----------+----------+----------+

Because the result of any arithmetic comparison with NULL is also NULL, you cannot obtain any meaningful results from such comparisons.由于使用NULL进行任何算术比较的结果也是NULL,因此您无法从此类比较中获得任何有意义的结果。

In MySQL, 0 or NULL means false and anything else means true. 在MySQL中,0NULL表示false,其他任何内容都表示trueThe default truth value from a boolean operation is 1.布尔运算的默认真值为1

This special treatment of NULL is why, in the previous section, it was necessary to determine which animals are no longer alive using death IS NOT NULL instead of death <> NULL.这种对NULL的特殊处理就是在上一节中有必要使用death IS NOT NULL而不是death <> NULL来确定哪些动物不再活着的原因。

Two NULL values are regarded as equal in a GROUP BY.GROUP BY中,两个NULL值被视为相等。

When doing an ORDER BY, NULL values are presented first if you do ORDER BY ... ASC and last if you do ORDER BY ... DESC.在执行ORDER BY时,如果执行ORDER BY... ASC,则NULL值最先出现,如果执行ORDER BY ... DESC,则NULL值最后出现。

A common error when working with NULL is to assume that it is not possible to insert a zero or an empty string into a column defined as NOT NULL, but this is not the case. 使用NULL时的一个常见错误是,假设不可能将零或空字符串插入定义为NOT NULL的列中,但事实并非如此。These are in fact values, whereas NULL means not having a value. 这些实际上是值,而NULL表示“没有值”。You can test this easily enough by using IS [NOT] NULL as shown:使用IS [NOT] NULL可以很容易地测试这一点,如图所示:

mysql> SELECT 0 IS NULL, 0 IS NOT NULL, '' IS NULL, '' IS NOT NULL;
+-----------+---------------+------------+----------------+
| 0 IS NULL | 0 IS NOT NULL | '' IS NULL | '' IS NOT NULL |
+-----------+---------------+------------+----------------+
|         0 |             1 |          0 |              1 |
+-----------+---------------+------------+----------------+

Thus it is entirely possible to insert a zero or empty string into a NOT NULL column, as these are in fact NOT NULL. 因此,完全可以在NOT NULL列中插入零或空字符串,因为它们实际上是NOT NULLSee Section B.3.4.3, “Problems with NULL Values”.请参阅第B.3.4.3节,“NULL值问题”