2016-09-10 37 views
0

我被困在這種情況下,不知道如何編寫選擇查詢,導致我想要的結果。這裏的情況是SQL - 如何連接3個表並選擇多列數

我有3代表會話,請求,登錄

會話表

# session table to store sessions data 
ID  user 
------------ 
1  John 
2  Sarah 

需求表

# request table to store `http` requests come to me 
ID  session 
------------ 
1  1 
2  1 
3  1 
4  1 
5  2 
6  NULL 

日誌表

# log table to store the logs that I record in my php code and store_ 
# them in the database while processing the requests 
ID  request 
------------ 
1  1 
2  1 
3  2 

我想什麼是選擇每個會話,並在本次會議提出的要求的數量,也可以是日誌的數量。我想要的結果是

#sessions result 
+----+-------+----------+------+ 
| ID | USER | requests | logs | 
+----+-------+----------+------+ 
| 1 | John | 4  | 3 | 
+----+-------+----------+------+ 
| 2 | Sarah | 1  | NULL | 
+----+-------+----------+------+ 

我做什麼是我使用的連接和通過會話組像

select session.*,count(request.id) as requests,count(log.id) as logs 
from session left join request on session.id=request.session 
left join log on request.id=log.request group by session.id 

問題是我這樣做的時候,如果1個請求有更在1日誌的情況下,它會被複制請求1,在我們的情況中有日誌1和2的情況下

# wrong result !! not what I want. notice the count of requests in session 1 
+----+-------+----------+------+ 
| ID | USER | requests | logs | 
+----+-------+----------+------+ 
| 1 | John | ((5)) | 3 | 
+----+-------+----------+------+ 
| 2 | Sarah | 1  | NULL | 
+----+-------+----------+------+ 

我在這裏做錯了什麼?

感謝

回答

1
select session.*,count(DISTINCT request.id) as requests,count(log.id) as logs 
from session left join request on session.id=request.session 
left join log on request.id=log.request group by session.id 
+0

我能說什麼呢? DISTINCTTTTTTTTTTT非常感謝你 –

1

只是試圖抓住我的方法。我沒有編譯查詢。 我要強調這一個

(select count(*) from log where request.id=log.request) 

完整的SQL

select session.id,session.user,count(request.id) as requests,logs from (
select session.*,(select count(*) from log where request.id=log.request) as  
logs from sesson join 
request on sesson.id=request.sesson group by request.id 
)group by session.id 
+0

謝謝先生你的時間,我會嘗試你的方法 –