Rails mysql - 1 个查询中有 2 个计数

Rails mysql - 2 counts in 1 query

我已经检查了一些其他答案,但无法将它们应用到我的查询中。我的杂务和完整的计数相互冲突。我试过 SUM 但没有用。如果我删除对另一个计数和相应 table 的引用,则这两个计数都会自行工作。

    @bays = Bay.
    select('COUNT(comp.id) as complete_count, COUNT(ch.count) as chore_count, comp.*, s.*, t.*, u.*, u.number as unit_number, b.*').
    from('bays b').
    joins('LEFT JOIN units u ON u.bay_id = b.id AND u.bay_id is not null').
    joins('LEFT JOIN sections s ON u.id = s.unit_id').
    joins('LEFT JOIN trades t ON s.trade_id = t.id AND t.production = 1').
    joins('LEFT JOIN completions comp ON t.id = comp.trade_id AND comp.unit_id = u.id').
    joins('LEFT JOIN chores ch ON t.id = ch.trade_id').
    joins('LEFT JOIN deficiencies d ON d.trade_id = t.id AND d.unit_id = u.id AND d.closed = 0').
    order("u.id, t.position").
    group("b.id, u.id, s.id, ch.id").
    group_by{|u| [u.id, u.number, u.unit_number]}

您必须计算两个 table 列的不同值:

@bays = Bay.
select('COUNT(DISTINCT comp.id) as complete_count, COUNT(DISTINCT ch.count) as chore_count, comp.*, s.*, t.*, u.*, u.number as unit_number, b.*').
from('bays b').
joins('LEFT JOIN units u ON u.bay_id = b.id AND u.bay_id is not null').
joins('LEFT JOIN sections s ON u.id = s.unit_id').
joins('LEFT JOIN trades t ON s.trade_id = t.id AND t.production = 1').
joins('LEFT JOIN completions comp ON t.id = comp.trade_id AND comp.unit_id = u.id').
joins('LEFT JOIN chores ch ON t.id = ch.trade_id').
joins('LEFT JOIN deficiencies d ON d.trade_id = t.id AND d.unit_id = u.id AND d.closed = 0').
order("u.id, t.position").
group("b.id, u.id, s.id, ch.id").
group_by{|u| [u.id, u.number, u.unit_number]}

基本上,COUNT 将计算每个非空值。您加入 table 的方式,如果一个 table 的匹配记录多于另一个,它会强制 MySQL 填补 'smaller' [=19= 的空缺] 具有重复值。通过添加 DISTINCT,您的计数将忽略这些值,从而为您提供正确的数字。