Group by with inner joins 返回太多记录

Group by with inner joins returning too many records

A table 有一个 foundStatus 列,它是一个字符。我想要 return 一个 foundStatuses 列表,每个状态旁边都有一个计数 - 这有效:

SELECT foundstatus, count(foundstatus) as total
FROM findings f
WHERE findDateTime BETWEEN '2008-01-01' AND '2017-06-24 23:59:59'
group by foundstatus
order by foundstatus

我需要加入几个 table 来构建一个 where 子句 - 这样做开始 return 太多列。我可以让它工作:

SELECT foundstatus, count(foundstatus) as total
FROM findings f left join
     pets p
     on f.petid = p.petid
WHERE findDateTime BETWEEN '2008-01-01' AND '2017-06-24 23:59:59' 
group by foundstatus
order by foundstatus

然而,通过进行左联接 - 我所做的任何后续联接(左联接或内联接)只是 returns 太多行(我猜是因为来自联接 tables 的多个记录被 returned):

SELECT foundstatus, count(foundstatus) as total
FROM findings f left join
     pets p
     on f.petid = p.petid inner join
     petTags pt
     ON p.petID = pt.petID 
WHERE findDateTime BETWEEN '2008-01-01' AND '2017-06-24 23:59:59' 
group by foundstatus
order by foundstatus

我需要一个类似 bottom only 的语句,其中 5 个连接 table 到 return 与前 2 个查询的计数相同。我确信这相当容易,但在 Google 上找不到任何东西 - 我该怎么做?谢谢

假设您在 findings 中有一个主键,您可以这样做:

select f.foundstatus, count(distinct f.findingsId) as total
from findings f left join
     pets p
     on f.petid = p.petid left join
     petTags pt
     on p.petID = pt.petID 
where f.findDateTime >= '2008-01-01' and
      f.findDateTime < '2017-06-25' 
group by f.foundstatus
order by foundstatus;

通常,count(distinct) 并不是最好的选择。我的猜测是 WHERE 子句中的 EXISTS 条件是执行您想要的操作的更好方法。