mysql - 多表关联查询的实现方法?
问题描述
Table ALogID UserId Date00001 0001 05-0100002 0002 05-0200003 0003 05-0200004 0004 05-0200005 0003 05-0300006 0001 05-03 00007 0002 05-03Table BUserId Status0001 Active0002 Active 0003 Active0004 InactiveTable CUserId Province0001 Yunnan0002 Fujian 0003 Fujian0004 Beijing
以上为数据库中的三张表,通过UserID关联。表A为用户登录信息表以LogID为主键;表B储存用户活跃状态,表C储存用户地理位置信息。现在想根据表A中的日期分组得到其他状态的数目累加和,预期返回结果为:
Date Active Inactive Yunnan Fujian Beijing05-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;
相关文章:
1. java - jvm 年轻代 如何回收 survivor 对象2. java - 对于jsp技术,aspx技术的困惑3. java - idea如何不显示.idea target这些文件夹4. docker-compose中volumes的问题5. python - Django有哪些成功项目?6. dockerfile - [docker build image失败- npm install]7. javascript - [,null]是什么用法8. docker - 各位电脑上有多少个容器啊?容器一多,自己都搞混了,咋办呢?9. javascript - vue vue-router 报$router重复定义10. apache - 怎么给localhost后面默认加上8080端口
