基本查询
select 字段列表 from 表名
基本查询
select * from person
* 通配符查询公司不能用
select id,name,age,sex,favourite from person
可以用as给字段起别名 as也可以省略
条件查询(模糊查询)
用where表示查询的条件
select id,name,age,sex,favourite from person where id between 1 and 10
select id,name,age,sex,favourite from person where id>5 and sex=‘男’
select id,name,age,sex,favourite from person where id>5 or sex=‘男’
%匹配0或者多个字符,一般不用左模糊(%放在左边,导致索引失效,降低查询效率)
select id,name,age,sex,favourite from person where name like ‘%豪’
_代表匹配一个字符
select id,name,age,sex,favourite from person where name like ‘_豪’
select id,name,age,sex,favourite from person where name like ‘%二%’
分页查询
排序 order by 字段名 (ASC 升序,DESC 降序)
select id,name,age,sex,favourite from person order by age ASC
select id,name,age,sex,favourite from person order by age DESC
聚合函数
聚合函数 count() sum() avg() max() min()
select count(0) from person 查询多少条记录
select sum(age) from person
select avg(age) from person
select min(age) from person
select max(age) 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 id from dept where name=‘鼓励部’)
内连接
笛卡尔积 查询出来的结果没有意义
select * from person,dept
显示内连接 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 [ouder] join 查询的是左边表的所有部分和右边表的交集
select p.id,p.name,age,sex,favourite,birth,d.id 部门id,d.name as deptname from person p left ouder join dept d on p.id=d.id
select p.id,p.name,age,sex,favourite,birth,d.id 部门id,d.name as deptname from person p left join dept d on p.id=d.id
右外连接 right [ouder] join 查询的是右边表的所有部分和左边表的交集
select p.id,p.name,age,sex,favourite,birth,d.id 部门id,d.name as deptname from person p right ouder join dept d on p.id=d.id
起别名
as 可以给字段名另外起个名字(两个表里的字段一样的情况下)
as 也可以用在表名上(表名有点长,写的麻烦)
左外连接和右外连接的区别:
左外是以左边的表为主表,查询的结果只关注左表,不在乎右边