SQL - 如何连接3个表并选择多个列的计数

时间:2016-09-10 02:19:47

标签: mysql 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

我想要的是是选择每个会话以及在此会话中发出的请求数量以及它的日志数量。我希望结果是

#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 |
+----+-------+----------+------+

我在这里做错了什么?

感谢

2 个答案:

答案 0 :(得分: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

答案 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