mysql - 多表关联查询的实现方法?
巴扎黑
巴扎黑 2017-07-04 13:44:12
0
1
1053
Table A
LogID    UserId    Date
00001    0001      05-01
00002    0002      05-02
00003    0003      05-02
00004    0004      05-02
00005    0003      05-03
00006    0001      05-03  
00007    0002      05-03

Table B
UserId    Status
0001      Active
0002      Active  
0003      Active
0004      Inactive

Table C
UserId    Province
0001      Yunnan
0002      Fujian  
0003      Fujian
0004      Beijing

以上为数据库中的三张表,通过UserID关联。表A为用户登录信息表以LogID为主键;表B储存用户活跃状态,表C储存用户地理位置信息。现在想根据表A中的日期分组得到其他状态的数目累加和,预期返回结果为:

Date    Active    Inactive    Yunnan    Fujian    Beijing
05-01   1         0           1         0         0   
05-02   2         1           0         2         1   
05-03   3         0           1         2         0

能否用一条SQL语句实现?

巴扎黑
巴扎黑

全部回复(1)
给我你的怀抱

这表业务逻辑非常不严密,我也就不严密的给你写一个了,就当你ABC表关系为多对一对一:

select 
    a.date,
    sum(case when b.status='Active' then 1 else 0 end) 'Active',
    sum(case when b.status='Inactive' then 1 else 0 end) 'Inactive',
    sum(case when c.province ='Yunnan' then 1 else 0 end) 'Yunnan',
    sum(case when c.province ='Fujian' then 1 else 0 end) 'Fujian',
    sum(case when c.province ='Beijing' then 1 else 0 end) 'Beijing'
 from a left join b on a.userid=b.user_id join c on a.user_id=c.user_id 
 group by a.date order by a.date;
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!