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. mysql優化 - mysql count(id)查詢速度如何優化?2. mysql主從 - 請教下mysql 主動-被動模式的雙主配置 和 主從配置在應用上有什么區別?3. angular.js - angularjs 用ng-reapt渲染的dom 怎么獲取上面的屬性4. 主從備份 - 跪求mysql 高可用主從方案5. css3 - [CSS] 動畫效果 3D翻轉bug6. node.js - node_moduls太多了7. angular.js - Angular路由和express路由的組合使用問題8. python如何不改動文件的情況下修改文件的 修改日期9. python - django 里自定義的 login 方法,如何使用 login_required()10. angular.js - 不適用其他構建工具,怎么搭建angular1項目
![css3 - [CSS] 動畫效果 3D翻轉bug](http://www.aoyou183.cn/attached/image/news/202304/110831f073.png)