一、单表查询语句
温馨提示
1、查询语句中使用一个或者多个表,表之间使用逗号(,) 分割。
2、使用 AND 或者 OR 指定一个或多个条件。
2、条件语句的值需要加单引号 ‘’ 。
3、表中有几条数据,是从0开始算的。
1.查询表中所有数据:
select * from 表
2.条件查询:
select * from 表 where age='23'
3.区间查询(and 、or)
-----------------------and-------------------
select * from 表 where age>='23' and age>='30'
等同于:
select * from 表 where age between '23' and '30'
--------------------------or-------------------
select * from 表 where age='23' or age='30'
等同于:
select * from 表 where age in('23','30')
4.逻辑运动算符
5.排序
正序 : select * from 表 order by 键/字段
倒序 : select * from 表 order by 键/字段 desc
6.模糊查询
select * from 表 where age like '%好%'
7.分页查询(后面必须是数字,不加引号)
从0开始查3条数据:
select * from 表 where limit 3
从第3条数据开始,查三条数据:
select * from 表 where limit 2,3
8.别名的命名(查询结果会改变,原表不会变 as可省略)
select name as 姓名 from 表
select name 姓名 from 表
9.聚合函数:最大值、最小值、平均值、求和、总条数
select max(age) from 表
select min(age) from 表
select avg(age) from 表
select sum(age) from 表
select count(*) from 表
10.子条件查询
select * from `hero` WHERE age=(SELECT max(age) FROM `hero`);
此时可声明变量:(用set @变量名=( ))
set @child=(SELECT max(age) FROM `hero`);
select * from `hero` WHERE age=@child;
11.分组函数
select type,SUM(age) from 表 group by type
注意:分组函数一般与聚合函数结合使用
12.分组函数的条件查询 (专用关键字 having )
select class,AVG(age) as avgage FROM study group by class HAVING avgage>30
二、查询语句顺序
书写顺序 | 语句 | 执行顺序 |
---|---|---|
1 | SELECT | 8 |
2 | DISTINCT <column> | 7 |
3 | FROM <表> | 1 |
4 | JOIN <关联> | 3 |
5 | ON <关联条件> | 2 |
6 | WHERE <条件> | 4 |
7 | GROUP BY <分组> | 5 |
8 | HAVING <排序> | 6 |
9 | ORDER BY <排序> | 9 |
10 | LIMIT <分页> | 10 |


