表记录查询
select语句语法格式
select column [all | distinct] from 数据源表 [where condition] [group by 分组字段] [having condition] [order by 排序字段 [asc | desc]]
指定查询条件
where condition1 运算符 condition2
比较运算
expression1 {= | < | > | <= | >= | <=> | !=} expression2
逻辑运算符
!,and,or
模式匹配
like 字符串表达式 [not] like 字符串
通配符
% 包含零个或多个字符组成的任意字符串
_任意一个字符
regexp match_expression [not][regexp | rlike] match_expression;
范围比较
- between
expression[not] between exp1 and exp2;
- in
expression in(exp1,exp2,…,expn);
空值比较
- is null
expression is [not] null;
数据分组
- group by
group by {column | expr | position} [asc | desc],…
- having 用于group by子句后
group by 分组字段 having condition
聚合函数
- count():用于统计组中满足条件的行数,返回select语句检索的行中非null值的数,若没有返回0
select count( {[all | distinct ] expression} | *) from tb-name ;
- max()/min():用于求表达式中所有值的最大/最小值
select max/min([all | distinct ] expression) from tb-name [where condition];
- SUM()/AVG():用于求和与平均值
select sum/avg([ all | distinct] expression) from tb-name [where condition];
- group_concat():将集合中的字符串连接起来,功能相似于concat()
select group_concat(’ ‘,’ ‘,’ ‘);
==concat(’ ‘,’ ‘,’ ');
- group by with rollup 在每个分组后加上一条汇总记录
- order by子句:对结果集进行排序
order by {column | expr | position} [asc | desc]
谓词限制select语句返回的行数
-
distinct column 避免记过出现重复记录
-
limit子句 查询前几条或中间某几条记录
select 字段列表 from 数据源 limit [start, ]length;(start 以0开始)
子查询 : 一般用于where子句或having子句中,与比较运算符或逻辑运算符一起构成where或having筛选条件
- IN:
expression [not] in (子查询语句)
expression {< | <= | > | >= | = | != | <>} {all | some | any } (子查询语句)
- EXISTS:
[NOT] exists (子查询语句)
连接运算
- 使用from子句指定数据源
from 表1 [连接类型] join 表2 on 表1 和表2之间的连接条件
内连接 inner join:from 表1 [inner] join 表2 on 表1 和表2 之间的连接条件
外连接 outer join
左连接 left join:from 表1 left join 表2 on 表1和表2之间的连接条件
右连接 right join:from 表1 right join 表2 on 表1 和表2 之间的连接条件
多表连接
from 表1 [连接类型] join 表2 on 表1 和表2 之间的连接条件 [连接类型] join 表3 on 表2和表3 之间的连接条件
- 合并结果集
union select column1 from 表1 union [all] select column2 from 表2….