zb_查
作者:互联网
目录
简单查询、连接查询
SELECT [DISTINCT] 列表 FROM 表名 [ORDER BY 列表 [ASC/DESC] LIMIT [[起始记录],显示行数]];
DISTINCT # DISTINCT 要求去掉重复数据
WHERE # 子句
SELECT 列名称 FROM 表名称 WHERE 列 运算符 值;
# 运算符 = !=or>< > < >= <= BETWEEN LIKE
# 值为文本 WHERE job='salesman';//是单引号不是那个
# 值为数值 WHERE sal=1250;
# 搭配AND OR 运算符
WHERE sal=1250 AND ename='ward';
WHERE job='salesman' OR job='manager'
--------------------------------------------
LIKE| NOT LIKE # 匹配符 模糊查询
# %通配符 % 是表示0个或多个字符
# 'N%' N开头 '%g'g结尾 '%s%'包含s的
# _ 是表示1个字符。
--------------------------------------------
IN | NOT IN
SELECT * FROM emp WHERE job IN ('salesman','clerk');
--------------------------------------------
BETWEEN AND | NOT BETWEEN AND
SELECT * FROM emp WHERE hiredate BETWEEN '1980-12-17' AND '1981-12-03';
SELECT * FROM emp WHERE sal BETWEEN 1000 AND 3000; # 包含边界
--------------------------------------------
SELECT * FROM t_users where id IN (1,3);
SELECT * FROM t_users where (id=1 or id=3);
# 以上两个查询结果相同,注意,和or的写法区别
# 查询blog表中id为1和3的数据,并非包含1和3
--------------------------------------------
UNION | UNION ALL # 操作符用于合并两个或多个 SELECT 语句(列数,数据类型,列的顺序相同)的结果集
UNION ALL # 不去重
UNION # 会去除重复数据
SELECT * FROM student where id < 4
UNION
SELECT * FROM student2 where id > 2 and id < 6
--------------------------------------------
IS NULL |IS NOT NULL
AS # 取别名
SELECT cno AS '课程号', stuscore+5 AS '成绩' FROM stumarks;/*文字别名*/
CROSS JOIN # 交叉链接笛卡尔积
INNER JOIN # 内连接
SELECT * FROM 表1,表2 WHERE 表1.字段名=表2.字段名
SELECT * FROM 表1 INNER JOIN 表2 ON 表1.字段名=表2.字段名
# 自链接:(是一种内连接)两个表是同一个表(必须需要起别名)
FROM 表1 AS a,表1 AS b
LEFT JOIN | RIGHT JOIN # 外连接:左外,右外
/*显示左/右表全部内容+从右/左表中关联的数据*/
/*查询没有选修课程的学生基本信息*/
SELECT stuinfo.*
FROM stuinfo LEFT JOIN stumarks ON stuinfo.stuno=stumark.stuno
WHERE stumarks.stuno is null;
嵌套子查询
SELECT * /*父*/
FROM stuinfo
WHERE stuno IN(SELECT DISTINCT stuno FROM stumarks);/*子*/
# 关键字
IN~
NOT IN~
EXISTS~ /*判断子查询的结果集是否不为空,返回true则外层查询语句执行*/
NOT EXISTS~
ALL~ /*所有值都满足条件*/
ANY~ /*至少满足一个条件*/
常用函数
SUM()# 求和
# 求平均
AVG()
SELECT avg(stuscore) AS 均分 FROM stumarks;
+----------+
| 均分 |
+----------+
| 78.84615 |
+----------+
# 统计
COUNT()
SELECT COUNT(DISTINCT cno) FROM stumarks;
+---------------------+
| COUNT(DISTINCT cno) |
+---------------------+
| 6 |
+---------------------+
# 最值
MAX() MIN()
SELECT MAX(stubirth),MIN(stubirth) FROM stuinfo;
+---------------+---------------+
| MAX(stubirth) | MIN(stubirth) |
+---------------+---------------+
| 1995-08-11 | 1994-10-12 |
+---------------+---------------+
排序分组
ORDER BY
# 默认升序(从小到大),降序请使用DESC关键字
SELECT * FROM emp ORDER BY sal;
SELECT * FROM emp ORDER BY sal DESC;
ORDER BY 1,2 desc;# 第一列升序,第二列降序
GROUP BY # 分组列名表------把记录进行分组
HAVING # 组筛选条件------筛选组
# 分组统计,如果分组字段值有null,null不会被忽略,会进行单独分段
# 使用GROUP BY实现分组时,可以指定多个分组字段进行分组,当多个字段取值都相同时就认为是同一组
# HAVING 只能在GROUP BY之后,且能使用函数。(对比:WHERE后不允许使用函数
SELECT cno,COUNT(stuno) ,AVG(stuscore)
FROM stumarks
GROUP BY cno /*属性名*/
HAVING AVG(stuscore)>=75
ORDER BY AVG(stuscore);
标签:stuno,WHERE,zb,查询,分组,stumarks,SELECT 来源: https://www.cnblogs.com/naitiam/p/16315875.html