實際開發中絕大多數查詢涉及多表關聯。本文從基礎語法到實戰範例,系統講解 MySQL 中 INNER JOIN、LEFT JOIN、RIGHT JOIN 的差異、適用場景與 PHP 整合示例,助你寫出高效、可讀的關聯查詢。
| JOIN 類型 | 結果集包含 | 典型場景 |
|---|---|---|
| INNER JOIN | 兩表匹配的行 | 只需雙方都存在的關聯數據(如:訂單+用戶) |
| LEFT JOIN | 左表所有行 + 右表匹配行(無匹配則 NULL) | 主表全量保留(如:所有用戶+其訂單,含無訂單用戶) |
| RIGHT JOIN | 右表所有行 + 左表匹配行 | 較少用,可改寫為 LEFT JOIN 互換表順序 |
-- tutorials_tbl:教程表
tutorial_id | tutorial_title | tutorial_author | submission_date
1 | Learn PHP | John Poul | 2007-05-24
2 | Learn MySQL | Abdul S | 2007-05-24
3 | JAVA Tutorial | Sanjay | 2007-05-06
-- tcount_tbl:作者教程統計表
tutorial_author | tutorial_count
mahran | 20
mahnaz | NULL
Jen | NULL
Gill | 20
John Poul | 1
Sanjay | 1
SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
FROM tutorials_tbl a
INNER JOIN tcount_tbl b ON a.tutorial_author = b.tutorial_author;
-- 結果:僅 John Poul (1) 和 Sanjay (1) 兩行
-- Abdul S、mahran 等無匹配行被過濾
SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
FROM tutorials_tbl a
LEFT JOIN tcount_tbl b ON a.tutorial_author = b.tutorial_author;
-- 結果:3 行
-- 1 | John Poul | 1
-- 2 | Abdul S | NULL -- 右表無匹配,補 NULL
-- 3 | Sanjay | 1
<?php
$mysqli = new mysqli("localhost", "root", "password", "TUTORIALS");
if ($mysqli->connect_errno) {
die("Connect failed: " . $mysqli->connect_error);
}
$sql = "SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
FROM tutorials_tbl a
LEFT JOIN tcount_tbl b ON a.tutorial_author = b.tutorial_author";
if ($result = $mysqli->query($sql)) {
while ($row = $result->fetch_assoc()) {
echo "Author: {$row['tutorial_author']} <br>";
echo "Count: {$row['tutorial_count']} <br>";
echo "Tutorial ID: {$row['tutorial_id']} <br>";
echo "--------------------------------<br>";
}
$result->free();
}
$mysqli->close();
?>
ON 條件欄位雙方必須有索引a、b 簡化欄位引用,提升可讀性ON 子句而非 WHERE(特別是 LEFT JOIN)IS NOT NULL,導致退化為 INNER JOIN掌握 JOIN 類型語義差異,配合索引設計與 EXPLAIN 分析,是寫出高效 SQL 的核心技能。實際項目中 90%+ 場景使用 INNER JOIN 與 LEFT JOIN 即可覆蓋。