通用語法
SELECT col1, col2, ...
FROM table1, table2 ...
[WHERE condition]
[ORDER BY col [ASC|DESC]]
[LIMIT offset, count]
核心選項說明
| 子句 | 作用 | 示例 |
| WHERE | 篩選條件 | WHERE status = 1 AND age > 18 |
| ORDER BY | 排序,默認 ASC 升序 | ORDER BY create_time DESC |
| LIMIT | 分頁/限制行數 | LIMIT 0, 10 (首頁10條) |
| OFFSET | 起始偏移(MySQL 常合併在 LIMIT) | LIMIT 10 OFFSET 20 |
| * | 查詢所有列(生產環境慎用) | SELECT * FROM users |
命令行查詢示例
mysql> SELECT * FROM tutorials_tbl;
+-------------+----------------+-----------------+-----------------+
| tutorial_id | tutorial_title | tutorial_author | submission_date |
+-------------+----------------+-----------------+-----------------+
| 1 | Learn PHP | John Poul | 2007-05-21 |
| 2 | Learn MySQL | Abdul S | 2007-05-21 |
| 3 | JAVA Tutorial | Sanjay | 2007-05-21 |
+-------------+----------------+-----------------+-----------------+
3 rows in set (0.01 sec)
PHP 三種獲取方式對比
<?php
$mysqli = new mysqli('localhost', 'root', 'rootpassword', 'TUTORIALS', 3306);
if ($mysqli->connect_errno) { die('連接失敗: ' . $mysqli->connect_error); }
$sql = "SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl";
$result = $mysqli->query($sql);
if (!$result) { die('查詢失敗: ' . $mysqli->error); }
// 1. 關聯數組:按列名訪問,推薦
while ($row = $result->fetch_assoc()) {
echo "ID: {$row['tutorial_id']} | 標題: {$row['tutorial_title']} | 作者: {$row['tutorial_author']} | 日期: {$row['submission_date']}<br>";
}
// 2. 數字索引數組:按位置訪問
// $result->data_seek(0); // 重置指針
// while ($row = $result->fetch_row()) { ... }
// 3. 兩者兼有:fetch_array(MYSQLI_BOTH)
// while ($row = $result->fetch_array(MYSQLI_BOTH)) { ... }
// 釋放結果集內存(大結果集必須)
$result->free();
// 關閉連接
$mysqli->close();
?>
性能與最佳實踐
- 避免 SELECT *:只查所需列,減少網絡傳輸和內存佔用。
- 大結果集分批處理:使用
LIMIT 分頁或游標,避免一次性載入導致 OOM。
- 釋放結果集:
$result->free() 及時釋放內存。
- 索引覆蓋:查詢列盡量包含在複合索引中,實現「覆蓋索引」避免回表。