[英]How to Count the number of Countries From registered users in my users table
I have two tables country
and users
.我有两个表country
和users
。 The country holds id's
for every country in the world.这个国家拥有世界上每个国家的id's
。 When a user registers into the system the id
of country is saved in a column named country
as a foreign key.当用户注册到系统中时,国家/地区的id
作为外键保存在名为country
/地区的列中。
Now what I want to do is to count how many countries users registered, for instance 3 users registered from the United States, It would show the name of the country and how many users registered from that country like this United States: 3
and so on, only for the countries that users registered from.现在我想做的是计算有多少个国家的用户注册了,例如 3 个用户从美国注册,它会显示国家的名称以及有多少用户从这个国家注册,比如United States: 3
等等, 仅适用于用户注册的国家。
Here is my Schema:这是我的架构:
users table用户表
country table:国家表:
Here is what I tried however I am not able to understand how to make it work properly:这是我尝试过的方法,但是我无法理解如何使其正常工作:
<?php
$query = $conn->prepare("SELECT users.id
AS userid, users.country AS country,
country.id AS countryID, country.country_name AS countryName
FROM users
LEFT JOIN country
ON country.id = users.country
WHERE users.name is not null;");
$query->execute();
while($row = $query->fetch()){
$countriesID = $row["countryID"];
$countryNames = $row["countryName"];
if($row["country"] == $countriesID){
$totalCountryq = $conn->prepare("SELECT COUNT(users.country) as c FROM users LEFT JOIN country ON users.country = country.id;");
$totalCountryq->execute();
if($row2 = $totalCountryq->fetchAll()){
$total = $row2['c'];
print_r($total);
}
}
//echo $countriesID;
}
?>
SELECT c.id, c.country_name, count(u.country) AS country_count
FROM counrty AS c
JOIN users AS u ON u.country = c.id
GROUP BY c.id
ORDER BY country_count DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.