MySQL 计数返回的行数超出应有的行数

标签 mysql count rows

我正在尝试计算给定查询的行数。但 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/

相关文章:

mysql - 在 MySQL 中对 2 个表进行分组而不进行连接

jquery - 如何在 HTML 表中查找行总计、列总计和总计值(该表本身是根据 AJAX 响应创建的)?

mysql - 计算 MYSQL 中具有特殊条件的重复条目

C++ - 将 std::count() 与抽象数据类型一起使用?

php - 获取最常用的带有特殊字符的单词

C# Count() 扩展方法性能

sql 将两行合并到同一个表中。 (用第二行数据更新第一行,然后删除第二行)

php - 在 HTML 中保存一个变量,这样用户只需输入一次信息

sql - 内部联接 - 使用相同联接的两个值!

mysql - mysql协议(protocol)中的身份验证有多安全?