MySql基础篇
条件查询
-- select 结果 from 表名 where 条件
-- 条件
-- =在where语句中表示是否相等 != < > >= <=
SELECT * FROM student WHERE score >= 70
SELECT * FROM student WHERE score = 98
SELECT * FROM student WHERE score != 70
SELECT * FROM student WHERE score > 70
-- 逻辑and or not
-- and且 between and
SELECT * FROM student WHERE score>=60 AND score<=80
SELECT * FROM student WHERE score BETWEEN 60 AND 80
-- or或者
SELECT * FROM student WHERE score>=60 OR score<=80
-- not非
SELECT * FROM student WHERE NOT score<=80
-- 模糊查询 like
-- like '张%' % 表示匹配多个字符 一个下划线表示匹配一个字符
SELECT * FROM student WHERE NAME LIKE '%三%'
SELECT * FROM student WHERE NAME LIKE '张__'
SELECT * FROM student WHERE NAME LIKE '张%'
-- IN(1,3) 筛选满足1或者3的
SELECT * FROM student WHERE grade=1 OR grade=3
SELECT * FROM student WHERE grade IN(1,3)
-- NOT IN(1,3)筛选不是1或者3的
SELECT * FROM student WHERE grade NOT IN(1,3)
-- 查询电话为空的
SELECT * FROM student WHERE phone IS NULL
-- 查询电话不为空的
SELECT * FROM student WHERE phone IS NOT NULL
-- union all 的效率比union的效率高
-- union 将多个查询结果合并,多个结果的列数必须相同,会去重
SELECT num,NAME,sex FROM student WHERE sex = '男'
UNION
SELECT num,NAME,sex FROM student WHERE score>60
-- union all 直接将查询到的数据简单的连接,不会去重排序
SELECT num,NAME,sex FROM student WHERE sex = '男'
UNION ALL
SELECT num,NAME,sex FROM student WHERE score>80
排序
-- order by 排序列 ASC/DESC
-- asc代表的是升序,desc代表的是降序
SELECT * FROM student ORDER BY num DESC
-- 首先按score进行降序排列,有重复项时按num降序排列
SELECT * FROM student ORDER BY score DESC , num DESC
-- 男生成绩按降序排列
SELECT *
FROM student
WHERE sex='男'
ORDER BY score DESC
-- limit 数量限制
-- 显示3个查询结果
SELECT * FROM student LIMIT 3;
-- 查询结果 开始位置,数量
SELECT * FROM student LIMIT 0,2; #分页,第一页
SELECT * FROM student LIMIT 2,2; #分页,第二页
SELECT * FROM student LIMIT 4,2; #分页,第三页
-- LIMIT 3 OFFSET 2 从第二个之后的三个查询结果
SELECT * FROM student LIMIT 3 OFFSET 2;
-- 分组查询 GROUP BY
-- 和分组函数一同查询的字段要求是group by 后的字段
SELECT sex,COUNT(*) FROM student GROUP BY sex
-- 查询男生各年级人数
-- 分组前数据过滤
SELECT grade,COUNT(*)
FROM student
WHERE sex='男'
GROUP BY grade
-- 查询那个性别人数大于2
-- 对分组后的数据进行条件过滤
SELECT *
FROM (SELECT sex,COUNT(*) c
FROM student
GROUP BY sex)t
WHERE t.c>2
-- having 对分组后结果进行筛选
SELECT sex,COUNT(*) c
FROM student
GROUP BY sex
HAVING c>2