1.完整语法(语法级别关键字的排列顺序如下)
SELECT 字段1,字段2,字段3... FROM 表名
WHERE 约束条件
GROUP BY 分组依据
HAVING 筛选
ORDER BY 排序的字段
LIMIT 限制条数
;
#必须要有的关键字如下:
SELECT * FROM 表名;
#关键字执行的优先级
FROM
WHERE
GROUP BY
HAVING
DISTINCT
ORDER BY
LIMIT
2.简单查询
SELECT * FROM 表名;
SELECT 字段1,字段2,字段3 FROM 表名;
SELECT DISTINCT 字段名 FROM 表名;
SELECT 字段名,字段名*12 AS 命名 FROM 表名;
SELECT CONCAT('组合的内容',字段名) AS 命名,CONCAT('组合的内容',字段名) AS 命名 FROM 表名;
SELECT CONCAT(字段名,"衔接内容",字段名) FROM 表名;
SELECT CONCAT(字段名,"衔接内容",字段名,"衔接内容",字段名) FROM 表名;
SELECT CONCAT_WS("衔接内容",字段1,字段2,字段3) AS 命名 FROM 表名;
#结合CASE语句:
SELECT
(
CASE
WHEN NAME = 'egon' THEN
NAME
WHEN NAME = 'alex' THEN
CONCAT(name,'_BIGSB')
ELSE
CONCAT(NAME, 'SB')
END
) as new_name
FROM
emp;
3.WHERE约束
SELECT * FROM EMP WHERE id >= 10 and id <=15;
SELECT * FROM EMP WHERE id BETWEEN 10 AND 15;
SELECT * FROM EMP WHERE id = 6 OR id = 9 OR id = 12;
SELECT * FROM EMP WHERE id IN (6,9,12);
_代表任意单个字符
%代表任意无穷个字符
SELECT * FROM EMP WHERE name LIKE "__";
SELECT * FROM EMP WHERE name LIKE "jin%";
SELECT * FROM EMP WHERE id NOT IN (6,9,12);
SELECT * FROM EMP WHERE id NOT BETWEEN 10 AND 15;
4.GROUP BY分组
什么是分组:
按照所有记录相同的部分进行归类,一定区分度低的字段
为何要分组:
当要以组为单位进行统计时就必须分组,分组的目的是为了以组为单位进行统计,再去考虑单条记录
注意:分组之后,只能查到分组的字段以及组内多条记录聚合的成果
SELECT * FROM 表名 GROUP BY 字段名;
5.聚合函数
MAX 最大值
MIN 最小值
AVG 平均值
SUM 总和
COUNT 计数
SELECT 字段名,COUNT(字段名) FROM 表名 GROUP BY 字段名;
SELECT 字段名,MAX(字段名) FROM 表名 GROUP BY 字段名;
SELECT 字段名,AVG(字段名) FROM 表名 GROUP BY 字段名;
#统计出每个部门年龄30以上的员工的平均薪资
SELECT post,AVG(salary) FROM emp WHERE age >= 30 GROUP BY post;
#注意:分组是在WHERE之后发生的
mysql> SELECT * FROM emp WHERE MAX(salary) > 3000;
ERROR 1111(HY000):Invalid use of group function
#GROUP_CONCAT
SELECT post,GROUP_CONCAT(NAME,':',AGE) FROM emp GROUP BY POST;
6.HAVING 过滤条件
WHERE是在分组之前的过滤,即在分组之前做了一次整体性的筛选
HAVING是在分组之后的过滤,即在分组之后专门针对聚合的结果进一步的筛选
SELECT post,avg(salary) FROM emp GROUP BY post HAVING AVG(salary) > 10000;
SELECT post,avg(salary) FROM emp GROUP BY post;
7.ORDER BY 排序
SELECT * FROM emp ORDER BY age ASC; #默认asc升序->从小到大
SELECT * FROM emp ORDER BY age DESC; #DESC降序->从大到小
SELECT * FROM emp ORDER BY age ASC,SALARY DESC; #先按照age升序排列,如果age相同则按照salary降序排
8.LIMIT 限制显示的条件
SELECT * FROM emp LIMIT 3;
#薪资最高的人的详细信息
SELECT * FROM emp ORDER BY SALARY DESC LIMIT 1;
#分页显示
SELECT * FROM emp LIMIT 0,5; #从0开始往后取5条
SELECT * FROM emp LIMIT 5,5; #从5开始往后取5条
9.正则表达式
SELECT * FROM emp WHERE name REGEXP "^jin.*(g|n)$";