基本格式
SELECT <列名> FROM <表名> WHERE <限制条件>;
mysql> create database company;Query OK, 1 row affected (0.00 sec)mysql> use company;Database changedmysql> show tables;Empty set (0.00 sec)mysql> create table employee ( name varchar(20) NOT NULL, age int );Query OK, 0 rows affected (0.02 sec)mysql> show tables;+-------------------+| Tables_in_company |+-------------------+| employee |+-------------------+1 row in set (0.00 sec)mysql> INSERT INTO employee VALUES ('Tom', 26), ('Jack', 24), ('Rose', 22), ('Jim', 35), ('Mary', 21), ('Alex', 26), ('Ken', 27), ('Rick', 24);Query OK, 8 rows affected (0.01 sec)Records: 8 Duplicates: 0 Warnings: 0mysql> SELECT * FROM employee;+------+------+| name | age |+------+------+| Tom | 26 || Jack | 24 || Rose | 22 || Jim | 35 || Mary | 21 || Alex | 26 || Ken | 27 || Rick | 24 |+------+------+8 rows in set (0.00 sec)mysql> SELECT name FROM employee;+------+| name |+------+| Tom || Jack || Rose || Jim || Mary || Alex || Ken || Rick |+------+8 rows in set (0.00 sec)mysql> SELECT name FROM employee WHERE age>25;+------+| name |+------+| Tom || Jim || Alex || Ken |+------+4 rows in set (0.00 sec)mysql> SELECT name FROM employee WHERE name='Mary';+------+| name |+------+| Mary |+------+1 row in set (0.00 sec)mysql> SELECT * FROM employee WHERE name='Mary';+------+------+| name | age |+------+------+| Mary | 21 |+------+------+1 row in set (0.00 sec)
Where
- WHERE 限制条件可以有数学符号 (
=,<,>,>=,<=) - WHERE 后面可以有不止一条限制,而根据条件之间的逻辑关系,可以用 [
条件一 OR 条件二] 和 [条件一 AND 条件二] 连接 - 取范围:
- <列名> BETWEEN a AND b; 注意BETWEEN AND是左右取的都是闭区间
- <列名> >= a AND <列名> <= b;
IN 和 NOT IN
- IN ():在选项中
- NOT IN (): 不在选项中
通配符
LIKE
- 接
_ (一个未指定字符) - 接
% (不定个未指定字符)
对结果排序
ORDER BY
- ASC:默认升序,从小到大
- DESC: 从大到小,降序排列
```sql
mysql> SELECT * FROM employee ORDER BY age DESC;
+———+———+
| name | age |
+———+———+
| Jim | 35 |
| Ken | 27 |
| Tom | 26 |
| Alex | 26 |
| Jack | 24 |
| Rick | 24 |
| Rose | 22 |
| Mary | 21 |
+———+———+
8 rows in set (0.00 sec)
<a name="nIGRa"></a>## AS对值进行重命名<a name="hCJAu"></a>## 计数、求和、平均、最大、最小SQL 有 5 个内置函数,这些函数都对 SELECT 的结果做操作:| 函数名: | COUNT | SUM | AVG | MAX | MIN || --- | --- | --- | --- | --- | --- || 作用: | 计数 | 求和 | 求平均值 | 最大值 | 最小值 |```sqlmysql> SELECT COUNT(age) FROM employee; +------------+| COUNT(age) |+------------+| 8 |+------------+1 row in set (0.00 sec)mysql> SELECT MAX(age) FROM employee;+----------+| MAX(age) |+----------+| 35 |+----------+1 row in set (0.00 sec)mysql> SELECT MAX(age) AS max_age FROM employee;+---------+| max_age |+---------+| 35 |+---------+1 row in set (0.00 sec)mysql> SELECT MAX(age) AS max_age, MIN(age) AS min_age FROM employee;+---------+---------+| max_age | min_age |+---------+---------+| 35 | 21 |+---------+---------+1 row in set (0.00 sec)mysql> SELECT MAX(age) AS max_age, MIN(age) AS min_age, AVG(age) as avg_age FROM employee;;+---------+---------+---------+| max_age | min_age | avg_age |+---------+---------+---------+| 35 | 21 | 25.6250 |+---------+---------+---------+1 row in set (0.00 sec)