-- 排序select*from stu groupby age ascselect*from stu groupby math descselect*from stu groupby math desc,english asc-- 如果数学成绩一样,再按英语升序-- 分组查询select 字段名 from 表名 [where 分组前条件限定]groupby[having 分组后条件过滤]-- 分组后,查询的字段为聚合函数和分组字段,查询其他字段无任何意义-- where和having的区别-- where是分组之前进行限定,不满足where条件,则不参与分组,而having是分组之后对对结果进行过滤-- where > 聚合函数 > havingselect sex,avg(math)from stu groupby sex
select sex,avg(math),count(*)from stu groupby sex
select sex,count(*),avg(math)from stu where math>70groupby sex
select sex,avg(math),count(*)from stu where math>70groupby sex havingcount(*)>2-- 约束的分类-- not null,unique,primary key,check,default,foreign key-- 外键约束droptableifexists emp
droptableifexists dept
createtable dept(
id intprimarykeyauto_increment,
dep_name varchar(20),
addr varchar(20));createtable emp(
id intprimarykeyauto_increment,
name varchar(20),
age int,
dep_id int,-- 添加外键,外键在主表关联constraint fk_emp_dept foreignkey(dep_id)references dept(id))-- 删除外键-- alter table emp drop foreign key fk_emp_dept-- 多表查询-- select * from emp,dept-- 隐式内连接select*from emp,dept where emp.dep_id = dept.id
-- 显示外连接select*from emp join dept on emp.dep_id = dept.id
-- 外连接,左外连接select*from emp leftjoin dept on emp.dep_id = dept.id
select*from emp rightjoin dept on emp.dep_id = dept.id
-- 子查询selectavg(age)from emp
select*from emp where age <=(selectavg(age)from emp)select*from emp where age =18or age =22select*from emp where id in(select id from emp where name ='张三'or name ='王五')select*from emp where age>=20;select*from(select*from emp where age>=20) t1 where t1.dep_id = dept.id