-2

I'm trying to get the number of records from 2 different tables history and records. I have 3 tables in my query, user, history, and records. All 3 tables have one column in common, userId.

A userId doesn't have to have a record in either the history or records tables. This is frustrating in that it's a fairly basic query that I can't get to work.

select u.userId, count(h.webId) `HistoryCount`, count(r.webId) `PRCount`
from user u
left join history h using(userId)
left join records r using(userId)
group by u.userId;

I would expect results like

|--------|--------------|---------|
| userid | HistoryCount | PRCount |
|--------|--------------|---------|
|   100  |       1      |    0    |
|   101  |       0      |    1    |
|   102  |       7      |    4    |
|--------|--------------|---------|

But I'm seeing results where both the HistoryCount and PRCount columns have the same values. I'm seeing results like

|--------|--------------|---------|
| userid | HistoryCount | PRCount |
|--------|--------------|---------|
|   100  |       1      |    1    |
|   101  |       1      |    1    |
|   102  |       7      |    7    |
|--------|--------------|---------|
4

1 回答 1

0

相关问题胜...

看来我需要在distinct我的每一count列中添加一个。

我编辑的查询,返回我期望的结果。

SELECT u.userId, count(DISTINCT h.webId) `HistoryCount`, count(DISTINCT r.webId) `PRCount`
FROM `user` u
LEFT JOIN history h USING(userId)
LEFT JOIN records r USING(userId)
GROUP BY u.userId
于 2013-04-28T16:05:33.060 回答