从主要 table 获取行,以及该记录在次要 table 中出现的次数计数(包括 0)
Get rows from primary table, and also a count of how many times that record appears in a secondary table (including 0's)
我有一个 Dogs table、一个 Kennels table 和 Visits table,其中包含 DogId 和 KennelId 列。
我正在尝试获取所有狗的完整列表,其中有一列显示对特定犬舍的访问次数,因此许多结果将包含 0 作为访问次数。
这是我试过的:
select dog.*, visits.visitCount FROM
(select * from Dogs) as dog,
(select COUNT (Visits.Id) as visitCount from Visits INNER JOIN Dogs ON Dogs.Id =
Visits.DogId where KennelId = 'E15A8C60-E0FE-472D-9CC4-08DA251A992F') as visits
按照这个说法,我得到了所有的狗,但所有狗的访问次数都相同,这是不正确的。我假设我的计数函数只执行一次,对剩余的行重复结果。我不知道如何纠正这个问题。任何帮助将不胜感激!
没有 table 模式或示例数据,猜测如下:
select d.*, Coalesce(v.VisitCount,0) VisitCount
from dogs d
left join (
select DogId, Count(*) VisitCount
from visits v
where v.KennedId = 'E15A8C60-E0FE-472D-9CC4-08DA251A992F'
group by DogId
)v on v.DogId = d.DogId;
我有一个 Dogs table、一个 Kennels table 和 Visits table,其中包含 DogId 和 KennelId 列。
我正在尝试获取所有狗的完整列表,其中有一列显示对特定犬舍的访问次数,因此许多结果将包含 0 作为访问次数。
这是我试过的:
select dog.*, visits.visitCount FROM
(select * from Dogs) as dog,
(select COUNT (Visits.Id) as visitCount from Visits INNER JOIN Dogs ON Dogs.Id =
Visits.DogId where KennelId = 'E15A8C60-E0FE-472D-9CC4-08DA251A992F') as visits
按照这个说法,我得到了所有的狗,但所有狗的访问次数都相同,这是不正确的。我假设我的计数函数只执行一次,对剩余的行重复结果。我不知道如何纠正这个问题。任何帮助将不胜感激!
没有 table 模式或示例数据,猜测如下:
select d.*, Coalesce(v.VisitCount,0) VisitCount
from dogs d
left join (
select DogId, Count(*) VisitCount
from visits v
where v.KennedId = 'E15A8C60-E0FE-472D-9CC4-08DA251A992F'
group by DogId
)v on v.DogId = d.DogId;