createtable students(id int, name char(6),foreignkey(class_id)references class(id));
六、单表记录查询
1、定义显示格式
select concat('姓名:',name,'年龄',age)as decs from students;
2、去重
selectdistinct name,age from students;
3、条件约束
select*from students where age>=18;# 单条件查询select*from students where age>=18and sex="男";# 多条件查询select*from students where age between18and25;# 范围查询select*from students where name in('hhq','zxy');# 包含查询select*from students where name like"黄%";# 模糊查询
4、分组查询
聚合函数
作用
max
最大值
min
最小值
avg
平均值
sum
总值
count
计数
select age,count(age) as '年龄人数' from students group by age;
5、过滤
select age,count(age) as '年龄人数' from students group by age having 年龄人数>25;
6、排序
select age from students order by age asc; # 升序,默认升序
select age from students order by age desc; # 降序
7、限数
select * from students limit 10;
七、多表记录查询
1、基础查询(本质)
select*from studends,class where students.cls_id=class.id;
2、内连接
select*from students innerjoin class on students.cls_id=class.id;# 查询2张表的共同部分
3、左连接
select*from students leftjoin class on students.cls_id=class.id;# 以左表为准,查询2张表的共同部分
4、右连接
select*from students rightjoin class on students.cls_id=class.id;# 以右表为准,查询2张表的共同部分
5、外连接
select * from students left join class on students.cls_id=class.id
union
select * from students right join class on students.cls_id=class.id; #同时以左表和右表为准,查询记录
八、视图
1、创建视图
createview 视图名 asselect*from students where age>18;
2、修改视图
alter view 视图名 as select * from students where age>20;