MySQL 查询数据

SELECT 的基础:选列、起别名、去重、限制条数。

Beginner
Key PointsSELECT 是 SQL 里用得最多的语句;先 SELECT 列再决定过滤与排序。

选列与别名

SQL
SELECT id, username, age
FROM users;

SELECT username AS name, age AS 年龄
FROM users;
Output
+----+----------+-----+
| id | username | age |
+----+----------+-----+
|  1 | alice    |  28 |
|  2 | bob      |  32 |
+----+----------+-----+

去重与限制

SQL
SELECT DISTINCT age FROM users;     -- 去重
SELECT * FROM users LIMIT 10;       -- 前 10 条
SELECT * FROM users LIMIT 5 OFFSET 10;  -- 跳过 10 取 5
Output
+-----+
| age |
+-----+
|  28 |
|  32 |
|  25 |
|  41 |
+-----+

算列与函数

SQL
SELECT username, CONCAT(username, '@', age) AS tag
FROM users;
Output
+----------+-----------------+
| username | tag             |
+----------+-----------------+
| alice    | alice@28        |
+----------+-----------------+
Avoid SELECT * on large tables — it reads every column. Select only what you need, and paginate with LIMIT offset, size.

Friends & Partners