MySql查询总结

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值