MySQL:使用GROUP BY时count(id)返回1而不是实际的总行数

时间:2012-12-14 15:02:06

标签: php mysql count group-by

我的查询在下面(它搜索父母和孩子4个级别上下)。这样,我得到一个“num”值中找到的行数:大约~22k行。

SELECT COUNT(fts_trip_id) AS num 
FROM feed_trips_se
JOIN departures ON d_departure_id=fts_trip_departure_id
JOIN destinations ON destinations.d_destination_id=d_departure_id
LEFT JOIN destinations AS destChild1 ON destChild1.d_destination_parent_id=destinations.d_destination_id
LEFT JOIN destinations AS destChild2 ON destChild2.d_destination_parent_id=destChild1.d_destination_id
LEFT JOIN destinations AS destChild3 ON destChild3.d_destination_parent_id=destChild2.d_destination_id
LEFT JOIN destinations AS destChild4 ON destChild4.d_destination_parent_id=destChild3.d_destination_id
LEFT JOIN destinations AS destParent1 ON destParent1.d_destination_id=destinations.d_destination_parent_id
LEFT JOIN destinations AS destParent2 ON destParent2.d_destination_id=destParent1.d_destination_parent_id
LEFT JOIN destinations AS destParent3 ON destParent3.d_destination_id=destParent2.d_destination_parent_id
LEFT JOIN destinations AS destParent4 ON destParent4.d_destination_id=destParent3.d_destination_parent_id
WHERE fts_trip_date>=NOW()
ORDER BY fts_trip_date ASC, fts_trip_price ASC

然而,由于我使用了大量LEFT JOIN,因此〜22k的数量不是正确的行程数量。我需要按实际的fts_trip_id对这些行进行分组。

不幸的是,当我执行GROUP BY时,我获得的行数与正确的行程数(~8k)相同,而不是获得正确行程数的单行。然后所有行都显示一个数字,通常是1,但也是10或13。

老实说,当我使用GROUP BY函数时,我不知道为什么我没有得到~8k的单行值。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:7)

您可以使用COUNT(DISTINCT)COUNT(DISTINCT fts_trip_id)来计算ID。 GROUP BY只会计算每个id的结果数。