语法:
select distinct 字段1,字段2... from 表名 where 条件 group by 组名 having 筛选 order by 排序 limit 限制条数
找到表:from
拿着where指定的约束条件,去文件/表中取出一条条记录
将取出的一条条记录进行分组group by,如果没有group by,则整体作为一组
执行select(去重):select * from 表名;
将分组的结果进行having过滤
将结果按条件排序:order by
限制结果的显示条数
优先级:from > where > group by> select > distinct> having>order by >limit
避免重复:distinct:
select distinct xx from 表名;
通过四则运算查询:
select xx(+ - * /) as 新名字 from 表名;
重命名:
select emp_name,salary*12 as annul_salary from employee;
select emp_name,salary*12 annul_salary from employee;
concat():用于连接字符串
select concat(‘姓名 :‘,emp_name),concat(‘年薪:‘,salary*12) from employee;
CONCAT_WS() 第一个参数为分隔符,select concat_ws(‘|‘,‘a‘,‘b‘,‘c‘)用管道符分割数据
结合CASE语句:case when语句 == if条件判断句
SELECT
(
CASE
WHEN emp_name = 'jingliyang' THEN
emp_name
WHEN emp_name = 'alex' THEN
CONCAT(emp_name,'_BIGSB')
ELSE
concat(emp_name, 'SB')
END
) as new_name
FROM
employee;
where 约束:select xx,xxx from 表名 where xx=="值";
比较运算符:> < >= <= <> !=
格式:select xx,xxx,xxxx from employee where 条件;
between 80 and 100 值在80到100之间(包括80和100)
格式:select xx,xxx,xxxx from employee where xx between xx and xx;
in(80,90,100) 值是80或90或100
SELECT 字段 FROM employee
WHERE 字段条件 in (xxxx,xx,xxxx,xxxx) ;
like ‘e%‘: 通配符可以是%或 _ ,%表示任意多字符,_ 表示一个字符
select * from 表名 where 字段名 like ‘xx%‘;
regexp 正则匹配:select * from employee where emp_name regexp ‘^jin‘
逻辑运算符:在多个条件直接可以使用逻辑运算符 and or not
关键字IS NULL(判断某个字段是否为NULL不能用等号,需要用IS)
select * from 表名 where 字段 is null;
GROUP BY分组聚合
单独使用:
select 字段名 from 表名 group by 字段名;
select * from 表 where 条件 group by 分组:加条件
GROUP BY关键字和GROUP_CONCAT()函数一起使用:
SELECT post,GROUP_CONCAT(emp_name) FROM employee GROUP BY post;#按照岗位分组,并查看组内成员名,
SELECT post,GROUP_CONCAT(emp_name) as emp_members FROM employee GROUP BY post;
GROUP BY与聚合函数一起使用
select post,count(id) as count from employee group by post;#按照岗位分组,并查看每个组有多少人
聚合函数:聚合函数聚合的是组的内容,若是没有分组,则默认一组
count(字段名):计数
max(字段名):最大值
min(字段名):最小值
avg(字段名):平均值
sum(字段名):求和
格式:
select count/sum/max/min/avg(字段名) from 表名;
select count/sum/max/min/avg(字段名) from 表名 where 条件;
having过滤(group by + 聚合函数):
执行优先级从高到低:where > group by > having
Where 发生在分组group by之前,因而Where中可以有任意字段,但是绝对不能使用聚合函数。
Having发生在分组group by之后,因而Having中可以使用分组的字段,无法直接取到其他字段,可以使用聚合函数
例子:查询各岗位内包含的员工个数小于2的岗位名、岗位内包含员工名字、个数
select post,emp_name,count(id) from employee group by post having count(id)<2
order by排序
单列排序:
select * from 表名 order by 字段名;默认升序
select * from 表名 order by 字段名 asc; 升序
select * from 表名 order by 字段名 desc;降序
多列排序:
例子:先按照age排序,如果年纪相同,则按照薪资排序
select * from 表名 order by age,salary desc;
select * from employee order by age desc,salary;
limit:限制查询记录数
select * from 表 order by 列 limit n; 取前n条
select * from 表 order by 列 limit m,n; 从m+1开始,取n条
select * from 表 order by 列 limit n offset m; 从m+1开始,取n条