查询语句
select * from 表 where 条件 [inner/left/right join 表1 on 条件] group by 列名 having 组 order by 列名 limit 开始偏移量,偏移长度(开始偏移量从0开始)
别名
select 字段 as 别名 from 表
where后的条件
select * from 表 where 条件 ; -》基础语法
MySQL运算符
操作符 | 说明 |
---|---|
= | 等于 |
<>或者 != | 不等于 |
< | 小于/(数字或者日期的比较) |
> | 大于/(大于) |
>= | 大于等于 |
<= | 小于等于 |
MySQL逻辑运算符
操作符 | 描述 |
---|---|
and | 且 |
or | 或者 |
not | 非 |
MySQL关键字说明
between:条件查询
[not] between 条件1 and 条件2 =》 包含等于
between cast('2013-01-01' as date) and cast('2018-05-06' as date)
cast() :类型转换函数
like:模糊查询
经常和通配符一起使用
%:任意字符长度
-:一个字符长度
\:转义字符
基础用法
select * from 表 where 字段 like '%like%'
in : 适合分类
select * from 表 where 字段 in (‘开始位置’,‘结束位置’)
find_in_set():第一个参数,要查找的字符串,第二个参数字段名
group by分组,也可以使用聚合函数
在筛选的基础上进行分类
select * from 表 where 条件 group by 字段1,字段2【分组条件】
实例
select fid,sum(nums) as nums from 表 group by fid;
(as 后可以跟中文名)
having:对分组后的数据进行过滤,使用聚合函数
select fid,sum(nums) as nums from 表 group by fid having nums > 100;
聚合函数
avg():计算平均值
count():计数
instr():返回子字符串中第一次出现的位置
sum():一组值的和
min():最小值
max():最大值
order by :排序
按照表数据默认位置进行排序,默认升序
可以指定多列排序,后排序在前排序的基础上【前排序有相同的值】进行排序
如果是汉字,则根据转换后的十六进制码的顺序排序,转换函数(hex(转换内容))
select 列名 from 表 order by 列1 [asc/desc],列2[asc/desc]
按照表达式排序
select id,pre*num as tos from 表 order by tos
自定义排序
select * from 表 order by field(gname,'字段值1','字段值2',。。。)
limit:取多少行
情况一
select * from 表 limit '开始偏移量,偏移长度'
情况二(前几个)
select * from 表 limit 数量
取前几条
SQL语句的执行顺序
from - join - on - where - group by - avg/sum… - having - select - distinct - order by
查询时间
不带时分秒
select current_date
带时分秒
select sysdate()/NOW()
date_format(logs.time,'%Y-%m-%d') as time(别名)
关联查询
表与表之间有关系,通过关系去查
select * from 表1 [inner/left/right/cross] join on 表2 on 条件
inner:交集
left:以左边的为主
right:以右边的为主
cross:交叉链接(笛卡儿积)
联合查询
把多个select语句查询的结果合并起来
列名为第一个查询语句的列名
默认去除重复项,all则不会去掉
也可以limit,order by等
select 列 from 表 union [all] select 列2 from 表
子查询
标量子查询
返回单一值的标量,最简单形式
select * from 表 where 字段=(select 字段 from 表 where 条件 order by ziduan desc limi 1)
列子查询
返回的结果集是N行1列
select * from 表 where 字段 in (select 字段 from 表 where 条件)
any/some
select * from 表 where 字段 < any(2,3)
小于最大值(不小于/大于其中的任意数据值)
all
select * from 表 where 字段 < all(2,3)
不大于/小于其中的全部数据,最值
行子查询
返回的结果是1行N列
select * from 表 where (列名1,列名2, .... ) in /=/...(条件)
表子查询
返回的结果集是N行N列
select * from logs where phone in (select phone from stu where classid i (select id from classes where fid in (...)))