首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> MySQL 資料庫 >> MySQL 綜合教學

MySQL NULL 值處理完全指南:IS NULL、<=> 運算符與 PHP 實戰

     編輯:MySQL 綜合教學

核心認知:NULL ≠ 空字符串 ≠ 0

  • NULL 表示「值未知/不存在」,佔用存儲空間(MyISAM 每列 1 bit,InnoDB 類似)
  • '' 空字符串是確定的「空值」,長度 0
  • NULL = NULL 結果是 NULL(非 true),'' = '' 為 true

三大專用運算符

運算符含義示例結果
IS NULL值為 NULLcol IS NULL → true/false
IS NOT NULL值不為 NULLcol IS NOT NULL → true/false
<=>空值安全等價(NULL=>true)NULL <=> NULL → true

命令行演示

mysql> CREATE TABLE tcount_tbl (tutorial_author VARCHAR(40) NOT NULL, tutorial_count INT);
mysql> INSERT INTO tcount_tbl VALUES ('mahran', 20), ('mahnaz', NULL), ('Jen', NULL), ('Gill', 20);

mysql> SELECT * FROM tcount_tbl WHERE tutorial_count = NULL;
Empty set (0.00 sec)  -- 錯誤寫法!

mysql> SELECT * FROM tcount_tbl WHERE tutorial_count IS NULL;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
| mahnaz          | NULL           |
| Jen             | NULL           |
+-----------------+----------------+

mysql> SELECT * FROM tcount_tbl WHERE tutorial_count <=> NULL;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
| mahnaz          | NULL           |
| Jen             | NULL           |
+-----------------+----------------+

索引與 NULL 的關係

  • B+ 樹索引不存儲全 NULL 的鍵值(InnoDB 單列索引全 NULL 不入索引,複合索引全 NULL 不入索引)
  • 允許 NULL 的列上建索引,查詢 WHERE col IS NULL 可能無法用索引(視版本/存儲引擎)
  • 最佳實踐:業務允許時優先 NOT NULL DEFAULT '' 或 DEFAULT 0,避免 NULL 帶來的語義模糊與索引限制。

PHP 處理 NULL

<?php
$mysqli = new mysqli('localhost', 'root', 'rootpassword', 'TUTORIALS', 3306);
$count = $_GET['count'] ?? null; // 可能為 null

if ($count !== null) {
    $sql = "SELECT tutorial_author, tutorial_count FROM tcount_tbl WHERE tutorial_count = ?";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param("i", $count);
} else {
    $sql = "SELECT tutorial_author, tutorial_count FROM tcount_tbl WHERE tutorial_count IS NULL";
    $stmt = $mysqli->prepare($sql);
}
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    echo "作者: {$row['tutorial_author']} | 數量: " . ($row['tutorial_count'] ?? 'NULL') . "<br>";
}
$stmt->close();
$mysqli->close();
?>

聚合函數與 NULL

  • COUNT(col) 忽略 NULL,COUNT(*) 計算行數包含 NULL
  • SUM/AVG/MIN/MAX 忽略 NULL
  • GROUP BY col 將所有 NULL 分為一組
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved