简体   繁体   English

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

[英]mySQL two COUNTS in one query with 3 tables involved

I have 3 tables namely: Town; 我有3张桌子,即:Town; Village; 村; Farmers...and I need to COUNT how many Farmers there are per Village, and how many Villages there are per Town. 农民...我需要计算每个村庄有多少个农民,以及每个镇有多少个村庄。 I'm new to php and mysql, so my code is still rubbish.. So far I have done the code for the query: 我是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);

It already outputs the correct counts like this: 它已经输出了正确的计数,如下所示:

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

It works well until I try to do a search for a specific town. 直到我尝试搜索特定城镇之前,它都能正常工作。 What happens is that the values of the Farmers column displays the correct value for the specified town. 发生的情况是“农民”列的值显示了指定镇的正确值。 But the whole table is still displayed with the farmers column of the other towns showing 0. 但是整个表格仍然显示,其他城镇的农民列显示0。

It shows this: 它显示了这一点:

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

But what I really want is this: 但是我真正想要的是:

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

But I don't know how to do it. 但是我不知道该怎么做。 And I've ran out of ideas. 而且我的想法已经用光了。 Please help me. 请帮我。

Does this solve the problem? 这样可以解决问题吗?

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

As there won't be any farmer to join with, the rows should be removed from the result set. 由于将没有任何农民可以加入,因此应将行从结果集中删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM