DQL:数据查询语言;用来对表内的数据进行查找。Database Query Language
SQL语句分为:基本查询、条件查询、聚合查询、分组查询、排序查询、分页查询。
SELECT 字段1,字段2,...FROM 表名;
SELECT *FROM 表名;
select name as '姓名', age as '年龄' from tt4;
#当然也可以不用加as
select name '姓名', age '年龄' from tt4;
select DISTINCT name from tt4;
可以发现name字段就只剩下一个张三了;
SELECT 字段名 RFOM 表名 WHERE 条件列表
条件:
比较运算符 | 功能 |
---|---|
> | 大于 |
>= | 大于等于 |
< | 小于 |
<= | 小于等于 |
= | 等于 |
<>或!= | 不等于 |
BETWEEN...AND | 在某个范围之内(含最小,最大值) |
IN(...) | 在in之后的列表中的值,多选一 |
LIKE 占位符 | 模糊匹配 (_匹配单个字符,%匹配任意个字符) |
IS NULL | 是NULL |
逻辑运算符
select * from tt4 where age=18;
select * from tt4 where age<18;
select * from tt4 where age<=18;
select * from tt4 where idcard is NULL or idcard='';
select * from tt4 where idcard is not NULL;
select * from tt4 where idcard;
select * from tt4 where age !=18;
select * from tt4 where age <>18;
注意between必须是先小后大,要不然查不出来数据,即使语句不报错。
select * from tt4 where age>=15 and age<=18;
select * from tt4 where age>=15 && age<=18;
select * from tt4 where age between 15 and 18;
select * from tt4 where age<25 and gender='女';
select * from tt4 where age=15 or age=18 or age=38;
select * from tt4 where age in (15,18,38);
(是_这个符号敲两下)一个下划线代表一个字符,两个下划线代表两个字符;
select * from tt4 where name like '__';
select * from tt4 where idcard like '%6';
select * from tt4 where name like '%三';
或者在X前面写够17个下划线也可以查询到
select * from tt4 where idcard like '_________________6';
将一列数据作为一个整体进行纵向计算
常见聚合函数
语法:注意聚合函数必须和字段名挨着。
SELECT 聚合函数(字段列表) FROM 表名;
select count(*) from tt4;
select avg(age) from tt4;
select max(age) from tt4;
select min(age) from tt4;
select sum(age) from tt4 where name like '_三_';
语法:
SELECT 字段列表 FROM 表名 [where条件] GROUP BY 分组字段名 [HAVING 分组后过滤条件];
where与having区别
执行时机不同: where是分组之前进行过滤,不满足where条件,不参与分组; 而having是分组之后对结果进行过滤。
判断条件不同: where不能对聚合函数进行判断,而having可以。
select count(*) from tt4 group by gender;
select gender, count(*) from tt4 group by gender;
select gender, avg(age) from tt4 group by gender;
select gender, count(*) from tt4 where age<38 group by gender;
select gender, count(*) from tt4 where age<38 group by gender having count(*)>=3;
#起别名gender_count
select gender, count(*) gender_count from tt4 where age<38 group by gender having gender_count>=3;
注意
·执行顺序: where >聚合函数>hving 。
·分组之后,查询的字段一般为聚合函数和分组字段,查询其他字段无任何意义。
语法:多字段排序,先按照第一个字段进行排序,才会根据第二个字段进行排序
SELECT 字段列表 FROM 表名 ORDER BY 字段1 排序方式1, 字段2 排序方式2;
排序方式
ASC:升序(默认值)
DESC:降序
select * from tt4 order by age;
select * from tt4 order by age ASC;
select * from tt4 order by age DESC;
select * from tt4 order by idcard, age DESC;
语法:
SELECT 字段列表 FROM 表名 LIMIT 起始索引,查询记录数;
注意
·起始索引从0开始,起始索引=,(查询页码-1)*每页显示记录数。
·分页查询是数据库的方言,不同的数据库有不同的实现,MySQL中是LIMIT。·如果查询的是第一页数据,起始索引可以省略,直接简写为limit 10。
select * from tt4 limit 2;
select * from tt4 limit 0,2;
select * from tt4 limit 2,2;
select * from tt4 limit a,2;
a=(页码-1)*页展示记录数
=(2-1)*2=2
完结撒花!!!!!!