mysql单表查询
1. 查找某个字段有哪些类型,可以用group by, 分组查询可以列出所有的类型
SELECT failure_reason FROM t_dispatch_log GROUP BY failure_reason;
2. 查找最新时间段的数据
sELECT * FROM t_dispatch_log where create_time > '2018-10-11 14:00:00' ORDER BY create_time DESC
3.需要5000条,5000条的导出数据
通过id来截取
sELECT * FROM t_dispatch_log where id>=1 and id<=5000
sELECT * FROM t_dispatch_log where id>=5001 and id<=10000
通过limit来截取
SELECT * from t_three_segment_code_log ORDER BY create_time DESC LIMIT 0,5000
SELECT * from t_three_segment_code_log ORDER BY create_time DESC LIMIT 5000,5000
SELECT * from t_three_segment_code_log ORDER BY create_time DESC LIMIT 10000,5000
limit的使用
limit 5000, 查出5000条数据
limit 10000,5000,查出以第10001条数据开始的5000条数据
group by, order by, limit和where没有关系,可以写在where条件后,也可以没有where条件直接用group by, order by, limit查询,limit写在查询语句最后
group by, having,order by, limit的使用顺序
Group by是用来进行分组查询的。having是用来对Group by 查询的结果进行筛选
HAVING类似于WHERE(唯一的差别是WHERE过滤行,HAVING过滤组)
在sql语句中有些函数,叫聚合函数:sum,count,avg,min,max,在这些方法可以和Group by一起使用。
连接查询 关键字join on,连接依据的列可能包含null值,null值不与任何值匹配,甚至和它本身
内连接分为:交叉连接(笛卡尔连接),相等连接,自然连接
[inner] join 内连接 等价于 等值连接,inner一般可以省略不写,
自然连接是一种特殊连接,它要求连接的两个表连接依据必须是相同的字段,字段名相同,字段属性相同,部分不支持自然连接
外连接分为:左外连接(LEFT OUTER JOIN),右外连接(RIGHT OUTER JOIN),全外连接(FULL OUTER JOIN)
说明:左表就是JOIN左边的表,右表是JOIN右边的表,这三种外连接中OUTER一般可省略不写
全外连接等价于左外连接和右外连接合计去掉重复的,即全外=左外 UNION 右外,MySQL不识别full join, 可以用全外=左外 UNION 右外
交叉连接:select * from table a cross join table b 等价于 select * from table a, table b
等值连接:select * from table a, table b where a.xx=b.yy
内连接:select * from table a (inner) join table b on a.xx=b.yy, 等价于上面等值连接
自连接:select * from table a as a1 join table a as a2 on a1.xx=a2.yy
select c.id, c.title, c.pid, p.title from areas as c inner join areas as p on c.pid = p.id where p.title = '山西省';
自然连接:select * from table a natrul join table b on a.xx=b.xx
左(外)连接:select * from table a left join table b on a.xx=b.yy
右(外)连接:select * from table a right join table b on a.xx=b.yy
全(外)连接:select * from table a full join table b on a.xx=b.yy