2014-11-14 47 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

相關問題