您的位置:首页 > 数据库 > MySQL

MySql查询总结

2015-08-21 16:15 344 查看
1.左连接: A left join B 的连接的记录数与A表的记录数同

左连接中 on 与where 条件的区别:where 是在left join之后在筛选符合条件的数据

2.右连接:A right join B 的连接的记录数与B表的记录数同

A left join B 等价B right join A

3.内连接:inner join on 两表匹配的记录显示在查询结果集中等价于where 条件查询

4.全外连接: FULL OUTER 是JOIN LEFT OUTER 和 RIGHT OUTER中所有行的超集,包含左、右两个表的全部行,不管另外一边的表中是否存在与它们匹配的行

5.自连接:join on ,自身连接是指同一个表自己与自己进行连接。这种一元连接通常用于从自反关系(也称作递归关系)中抽取数据。例如人力资源数据库中雇员与老板的关系。

下面例子是在机构表中查找本机构和上级机构的信息。

select s.inst_no superior_inst, s.inst_name sup_inst_name, i.inst_no, i.inst_name

from t_institution i

join t_institution s

on i.superior_inst = s.inst_no

结果是:

superior_inst sup_inst_name inst_no inst_name

800 广州市 5801 天河区

800 广州市 5802 越秀区

800 广州市 5803 白云区

实例:统计某时间段客户各跟踪状态,要求没有客户跟踪状态的变更也需要显示,track_state客户跟踪状态字典表,customer_history客户变更历史记录表

select ts.name,ts.id,count(tch.new_track_state_id) as counts,

case when ts.id=1 then 'red'

when ts.id=2 then 'orange'

when ts.id=3 then 'yellow'

when ts.id=4 then 'green'

when ts.id=5 then 'blue'

when ts.id=6 then 'purple'

when ts.id=7 then 'lilac'

end as color from track_state ts left join (

select ch.new_track_state_id from customer_history ch ,(select t.customer_id,max(t.change_time) as change_time from customer_history t where t.change_time between date_format('20160801','%Y%m%d')

and date_format('20160831','%Y%m%d') group by t.customer_id ) as temp where temp.customer_id=ch.customer_id and temp.change_time=ch.change_time ) as tch

on tch.new_track_state_id=ts.id and tch.new_track_state_id is not null

group by ts.id order by ts.id;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: