2014-11-14 46 views
0

我正在尝试计算给定查询的行数。但count会返回比它应该更多的行。发生什么事?MySQL计数返回比它应该更多的行

该查询只返回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`; 
+0

您在此表中有多少条记录?并且,如果您将删除JOIN,请检查查询是否正确计算。 – 2014-11-14 13:49:46

+0

尽管(刺激)更具有表演性,但在没有任何聚合函数的情况下,使用GROUP BY子句(在您的第一个查询中)是不恰当的并且经常会引起误解。也许你正在考虑DISTINCT - 虽然在对'SELECT *'使用时没有任何意义(在正确数据库中) – Strawberry 2014-11-14 14:46:44

回答

0

当您选择count(*)时,它将在group by之前进行计数。你可能(不幸的是我的领域是SQL Server,我没有一个mySQL实例来测试)通过使用over()函数来解决这个问题。

例如:

select count(*) over (partition by `opportunities`.`id`) 

编辑:其实不像,这是可以在MySQL中,我的坏。如果只是将整个事情包装在一个新的陈述中?这不是最优雅的解决方案,但会给你你想要的数字。

+0

或只是删除答案 – Strawberry 2014-11-14 14:47:14

相关问题