mysql - 多表關聯查詢的實作方法?
巴扎黑
巴扎黑 2017-07-04 13:44:12
0
1
1057
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學習者快速成長!