mySQL两个COUNTS在一个查询中涉及3个表

时间:2012-03-22 01:38:11

标签: php sql

我有3张桌子:镇;村;农民......我需要计算每个村庄有多少农民,每个城镇有多少个村庄。我是php和mysql的新手,所以我的代码仍然是垃圾。到目前为止,我已经完成了查询的代码:

$query = "SELECT *, COUNT(DISTINCT village.villageID) AS cnt_village, 
COUNT( farmer.farmerID ) AS cnt_farmers
FROM town LEFT JOIN village ON village.townID = town.townID
LEFT JOIN farmer ON farmer.villageID = village.villageID
GROUP BY town.townID
ORDER BY town.townName";
$result = mysql_query($query);

它已经输出了正确的计数:

----TOWN--------VILLAGES----FARMERS-----
| Caibiran   |      2     |    23       |
| Culaba     |      7     |    39       |
|      TOTAL |      9     |    62       |

在我尝试搜索特定城镇之前,它运作良好。会发生什么是Farmers列的值显示指定城镇的正确值。但是整个表格仍然显示在其他城镇的农民专栏显示0。

它显示了这个:

 ----TOWN--------VILLAGES----FARMERS-----
| Caibiran   |      2     |    23       |
| Culaba     |      7     |    0        |
|      TOTAL |      9     |    23       |

但我真正想要的是:

----TOWN--------VILLAGES----FARMERS-----
| Caibiran   |      2     |    23       |
|      TOTAL |      2     |    23       |

但我不知道该怎么做。我已经没有想法了。请帮帮我。

1 个答案:

答案 0 :(得分:1)

这是否解决了这个问题?

SELECT *, COUNT(DISTINCT village.villageID) AS cnt_village, 
COUNT( farmer.farmerID ) AS cnt_farmers
FROM town
JOIN village ON village.townID = town.townID
JOIN farmer ON farmer.villageID = village.villageID
GROUP BY town.townID
ORDER BY town.townName

由于没有任何农民加入,因此应从结果集中删除行。