使用这些表格:
Table name: Fields:
Users userID
F fID,userID
B total,userID,bID
L lID,bID
Users.userID是“key”,它与其他表的关系是:
F.userID与Users.userID相同 B.userID与Users.userID相同 L.bID与B.bID相同
对于每个Users.userID,我需要显示:
f中该userID的fID计数,
B中该userID的所有'总和的总和
所有带有bID的BID的LID的计数在L.左侧
(看下面的查询后会更清楚:)
我试过了:
SELECT Users.userID, COUNT(F.fID) as 'fcount', SUM(B.total) as 'bcount', COUNT(L.lID) as 'lcount'
FROM Users
JOIN F ON F.userID=Users.userID
JOIN B ON B.userID=Users.userID
JOIN L ON L.bID=B.bID
GROUP BY Users.userID
现在,'count'列显示不合理的高数字,这些数字并不反映我希望获得的数据,而且我不知道它们来自哪里(并且不需要,只需要知道如何获得正确的数量:))。
谢谢。
答案 0 :(得分:1)
对于左侧的每一行,连接重复右侧的每个匹配行。如果您连接多个表,则会重复更多行。
例如,假设客户有五个订单和两个地址。然后,以下查询将返回1 x 5 x 2 = 10行:
select *
from Customer c
join [Order] o
on o.CustomerID = c.ID
join Address a
on a.CustomerID = c.ID
where c.ID = 42
如果您计算此行集的订单总数,您将获得两倍的金额,因为每个地址都会重复每个订单。
这通常通过子查询解决,子查询保证每组只返回一行:
select u.userID
, fcount
, bcount
, lcount
from Users u
join (
select UserID
, count(*) as fcount
from F
group by
UserID
) F
on F.UserID = u.UserID
join (
select UserID
, sum(*) bcount
from B
group by
UserID
) B
on B.UserID = u.UserID
join (
select B.UserID
, count(*) lcount
from B
join L
on L.bID = B.bID
group by
B.UserID
) L
on L.UserID = u.UserID