赞
踩
自定义两张数据测试表:student 、class
学生表:中文名、年龄、性别、暴击率、住址、班级id、入学时间
班级表:中文名、英文名、创建时间
一:条件查询 where
# 查询年龄小于22并且是女性的学生信息
- select * from student
- where age < 22 and gender = '女';
结果:
# 查询7年前入学的学生信息
- select * from student
- where create_time < DATE_SUB(CURDATE(),INTERVAL 7 year)
结果:
二:去重查询 distinct
# 查询学生表有哪些地址
select distinct address from student
结果:
三:拼接查询 concat
# 将暴击率加上百分号
select name_cn,CONCAT(hit_rate,'%') as hit_rate from student
结果
# 将姓名与年龄通过字符拼接输出
select CONCAT(name_cn,'/',age) as name_age from student
结果:
三:排序查询 order by
# 查询地址为弗雷尔卓德的学生,并且根据age排序(升序)
- select name_cn,age from student
- where address = '弗雷尔卓德' ORDER BY age
结果:
# 查询地址为弗雷尔卓德的学生,并且根据age排序(降序)
- select name_cn,age from student
- where address = '弗雷尔卓德' ORDER BY age DESC
结果:
四:分组查询 group by
# 查询每个address分别总共有多少男学生,并且根据数量排序(升序)
- select address,COUNT(id) as Num from student
- where gender = '男'
- GROUP BY address ORDER BY Num
结果:
# 查询每个address分别总共有多少学生,并且筛选出数量大于2的,最后再排序(升序)
- select address,COUNT(id) as Num from student
- GROUP BY address
- HAVING Num > 2 ORDER BY Num
结果:
五:关联查询
1)left jion (左连接)
左连接以左边的表为主要查询表,左边有,右边无,则以None填充
# 查询每个班级分别有那些学生
- select class.name_cn as className,
- student.name_cn as studentName from class
- left join student on class.id=student.class_id
- ORDER BY class.id
结果:因为战术班没有学生,所以查询结果中以None补充
2)right join (右连接)
右连接以右边的表为主要查询表,右边有,左边无,则以None填充
# 查询每个学生对应的班级
- select class.name_cn as className,
- student.name_cn as studentName from class
- right join student on class.id=student.class_id
- ORDER BY class.id
结果:因为伊泽瑞尔的class_id=0,他并没有对应的班级,所以查询结果中他的班级是空
持续更新...
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。