-- 中文排序 select*from student orderbyconvert(name using gbk)
聚合函数
count 统计
1 2
selectcount(*) from student; ==> 只要有值就统计 count(name)
max 最大值
1
selectmax(age) from student;
min 最小值
1
selectmin(age) from student;
sum 求和
1
selectsum(age) from student;
avg 平均值
1
selectavg(age) from student;
分组
group by 根据某一字段排序,可以去重
1 2
-- 每个班级的平均,最大年龄 select class, avg(age), max(age) from student groupby class;
连接查询
等值查询
1
select*from student as stu, score as sc where stu.sid = sc.sid;
内查询
1 2
select*from student as stu innerjoin score as sc on stu.sid = sc.sid;
多表连接 (两两之间产生条件)
1 2 3
select*from student as stu innerjoin score as sc on stu.sid = sc.sid innerjoin course as co on sc.cid = co.cid;
自关联(同一个表查询多次,自己产生关联,表必须起别名)
1 2
select*from areas as sheng innerjoin areas as shi on sheng.pid = shi.pid
左连接(jion 前边的表)
1 2
select*from student as stu leftjoin score as sc on stu.sid = sc.sid;
右连接
1 2
select*from student as stu rightjoin score as sc on stu.sid = sc.sid;
子查询
1 2
-- 查询大于平均年龄的学生 select*from student whrer age > (selectavg(age) from student);
数据分表
1 2 3 4 5 6 7 8 9 10 11 12 13
create table newStudent ( id int unsigned primary key auto_increment, name varchar(10), age int unsigned ) -- 查询的数据插入到另一个表中(查询出来的列必须对应表中的字段名,否则会新建) insert into newStudent(id, name, age ) select id,name,age from student;
-- 创建并直接插入(查询出来的列必须对应表中的字段名,否则会新建) create table newStudent ( id int unsigned primary key auto_increment, Sname varchar(10) ) select name as Sname from student;
-- 建表时创建索引 key (age)、primary key、unique create table newStudent ( id int unsigned primary key auto_increment, name varchar(10) unique age int unsigned, key (age) )
-- 已经存在的表创建索引 create index 索引名称 on 表名(字段名(长度)) create index i_index on newStudent(name(10))