2016-09-10 4 views
0

私はこのような状況に陥っているため、結果として選択クエリを書く方法がわかりません。ここで私は3つのテーブルセッションを持っている状況SQL - 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 
は、各セッションとこのセッションで行われた要求の数を選択することであり、またそれがログの数です。私は私は

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件のリクエストが多くを持っている場合、問題は、ある結果は

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

になりたいです1ログよりも多い場合、ログ1と2を持つこの状況の要求1のように結合によって複製されます。

# 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

を強調表示する必要がありますか? DISTINCTTTTTTTTT非常に非常にありがとうございます –

1

はちょうど私のアプローチをキャッチしてみてください。私はクエリをコンパイルしていません。 は、私が何を言うことができ、この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

お時間をいただきありがとうございました、私はあなたのアプローチを試してみます –

関連する問題