Appearance
MySQL单表查询
语法:
select distinct 字段1,字段2[,...] from 表名 where条件
group by field having 筛选条件 order by filed limit 条数 解释说明: distinct 查重 group by field ;一般是某个字段或多个字段,field就是字段的意思 having 主要配合group by使用,对,里面可以使用聚合函数 order by filed 排序,升序 降序,一般是某个字段或多个字段 limit 限制查出数据条数 优先级:
- from
- where
- group by
- select
- distinct
- having
- order by
- limit 解释说明: 1.先找到表:from 2.拿着where指定的约束条件,去表中取出符合条件的一条条数据 3.将取出的数据进行分组group by,如果没有group by,则每行为一组 4.执行select查询所指定的字段 5.若有distinct则去重 6.将结果按照条件排序 order by 7.限制结果的显示条数 limit
条件where
男员工的相关信息 select * from emp where sex='male' 比较运算符有 大于 > 大于等于 >= 小于 < 小于等于 <= 不等于 <> != SELECT * FROM employees WHERE salary >= 50000; SELECT * FROM users WHERE username != 'runoob';
is null/is not null
select * from emp where post is not null select * from emp where post is null
多条件
薪资大于等于1万,部门为教学部的员工信息 select * from emp where salary >=1000 and office= 401 或关系用 or ,并列关系用 and
包含 in/not in
-- 相当于 office = 401 or office=402 select * from emp where office in (401,402)
between...and
select * from emp where salary between 1000.37 and 3500
like模糊查询
针对字符串包含某个值 通配符,;_ 表示 1个字符 例如,'a%' 匹配以字母 'a' 开头的任何字符串 ;'r%' 匹配第二个字母为 'r' 的任何字符串
LIKE 'a%o'; 匹配以字母 'a' 开头,然后是零个或多个字符,接着是 'o',最后是一个任意字符的字符串,如 'apple'、'apolo' LIKE 'smi%' COLLATE utf8mb4_general_ci; 将选择姓氏以 'smi' 开头的所有员工,不区分大小写
-- 查询员工姓名带h的: select * from emp where emp_name like '%h%'
select * from emp where emp_name like '_h%' 注意:huahua 名字以h打头,用 like '%h%'能查出来,用 like '_h%' 查不出来,因为_要求h前面需要有1个字符
group by 分组
分组字段和查询字段必须一致
每个部门的员工人数 select office,count(emp_name) 员工个数 from emp group by office
having分组后过滤条件
-- 查找大于5个员工数以上的部门 select office,count(emp_name) 员工个数 from emp group by office having count(emp_name)>5
group_concat select office, group_concat(emp_name) 员工个数 from emp group by office
常用聚合函数
count() 计数 sum() 求和 avg() 求平均 max() 最大值 min() 最小值
排序order by
limit
-- limit m,n ( m 可省略,省略时m=0) 是先把所有数据查出来,再限制条数, 从下标0,第1条,开始查10条 SELECT * from stu limit 10 从下标5,第6条,开始查10条 SELECT * from stu limit 5,10
去重distinct
SELECT type FROM tool_entry 图片没显示完,后面还有 SELECT DISTINCT type FROM tool_entry
distinct关键字可以用在SELECT语句的开头,并在查询结果中显示唯一的行。 用在所有字段前,对所有字段起作用
select id,distinct name from user #mysql会报错,因为
拼接concat
方法1 方法2
条件判断case when
case when 结合聚合函数 401办公室,薪资大于1万有3人;403有5人 薪资大于10000的数据,赋值为 emp_name count计数时,null是不参与计数的 另一种表达
区别:402办公室没有薪资过万的,直接被 where子句过滤掉了;case when可以显示402办公室 说明where 一开始就过滤掉了不符合条件的