一、基本查询
#select 字段列表 from 表名
SELECT id,name,age,sex,favourite from person
二、条件查询
# 用where表示查询的条件
SELECT id,name,age ,sex ,favourite from person where id BETWEEN 1 and 10
# %匹配0或多个字符,一般不用左模糊(%放在左边,导致索引失效,降低查询效率)
SELECT id,name,age ,sex ,favourite from person where name like '%豪'
# _代表匹配一个字符
SELECT id,name,age ,sex ,favourite from person where name like '_豪'
三、分页查询
# 语法 limit 起始索引,个数
# 分页查询第m页,每页展示n 条数据 limit (m-1)*n, n
#limit 0,5 0索引 , 5从0索引开始往后数5个
SELECT id,name,age ,sex ,favourite from person limit 0,5
四、 排序
# 排序 order by 字段名 (ASC 升序,DESC降序)
SELECT id,name,age ,sex ,favourite from person ORDER BY age ASC;
五、聚合函数
# 聚合函数 count() sum() avg() max() min()
select count(0) from person 查询有多少条记录
SELECT CAST(avg(age) as decimal(10,0)) as avg from person
六、分组查询
# 分组查询 group by 字段
SELECT sex,count(0),avg(age) from person GROUP BY sex;
# having条件查询 where分组前,having分组后的条件
SELECT sex,count(0),avg(age) from person where age>8 GROUP BY sex having avg(age)>20;
七、子查询
# 把查询到的结果当作另一个查询的条件
SELECT id,name,age ,sex ,favourite from person where id in (SELECT pid from dept where name='鼓励部')
八、内连接
# 显示内连接 inner可以省略
select * from person INNER JOIN dept on person.id=dept.pid
select * from person JOIN dept on person.id=dept.pid
select p.id,p.name,age,sex,favourite,birth,d.id deptid,d.name deptname,pid from person p JOIN dept d on p.id=d.pid
# 隐式内连接
select * from person,dept where person.id=dept.pid
九、外连接
# 左外连接 left [outer] join 查询的是左边表的所有部分和右边表的交集
select p.id,p.name,age,sex,favourite,birth,d.id 部门id,d.name as deptname,pid from person p left outer join dept d on p.id=d.pid
# 右外连接 right [outer] join 查询的是右边表的所有部分和左边表的集 select p.id,p.name,age,sex,favourite,birth,d.id 部门id,d.name as deptname,pid from person p right outer join dept d on p.id=d.pid