我正在尝试计算给定查询的行数。但 count 返回的行数超出了应有的行数。发生了什么事?
此查询仅返回 1 行。
select *
from `opportunities`
inner join `companies` on `opportunities`.`company_id` = `companies`.`id`
left join `opportunityTags` on `opportunities`.`id` = `opportunityTags`.`opportunity_id`
where `opportunities`.`isPublished` = '1' and `opportunities`.`Company_id` = '1'
group by `opportunities`.`id` ;
此查询返回有 3 行。
select count(*) as aggregate
from `opportunities`
inner join `companies` on `opportunities`.`company_id` = `companies`.`id`
left join `opportunityTags` on `opportunities`.`id` = `opportunityTags`.`opportunity_id`
where `opportunities`.`isPublished` = '1' and `opportunities`.`Company_id` = '1'
group by `opportunities`.`id`;
最佳答案
当您选择 count(*) 时,它会在 group by 之前进行计数。您也许可以(不幸的是我的领域是 SQL Server,并且我没有要测试的 mySQL 实例)通过使用 over() 函数来修复此问题。
例如:
select count(*) over (partition by `opportunities`.`id`)
编辑:实际上看起来这在 mySQL 中不可用,我的错。将整个事情包装在一个新的 select 语句中怎么样?这不是最优雅的解决方案,但会给你你想要的图形。
关于MySQL 计数返回的行数超出应有的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26931394/