-- 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; +-------------+-----------------+----------------+ | tutorial_id | tutorial_author | tutorial_count | +-------------+-----------------+----------------+ | 1 | John Poul | 1 | | 3 | Sanjay | 1 | +-------------+-----------------+----------------+
只有 John Poul、Sanjay 兩表都有,Abdul S 被過濾。
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; +-------------+-----------------+----------------+ | tutorial_id | tutorial_author | tutorial_count | +-------------+-----------------+----------------+ | 1 | John Poul | 1 | | 2 | Abdul S | NULL | | 3 | Sanjay | 1 | +-------------+-----------------+----------------+
Abdul S 保留,tutorial_count 為 NULL。
<?php
$mysqli = new mysqli('localhost', 'root', 'rootpassword', 'TUTORIALS', 3306);
if ($mysqli->connect_errno) { die('連接失敗: ' . $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";
$result = $mysqli->query($sql);
if (!$result) { die('查詢失敗: ' . $mysqli->error); }
while ($row = $result->fetch_assoc()) {
echo "作者: {$row['tutorial_author']} | 數量: {$row['tutorial_count']} | ID: {$row['tutorial_id']}<br>";
}
$result->free();
$mysqli->close();
?>
LEFT JOIN ... ON a.id = b.id AND b.status=1(過濾右表)vs LEFT JOIN ... ON a.id = b.id WHERE b.status=1(變相變內連接)。ON a.col = b.col 兩側列均應建索引。