繁体   English   中英

如何计算我的用户表中注册用户的国家/地区数量

[英]How to Count the number of Countries From registered users in my users table

我有两个表countryusers 这个国家拥有世界上每个国家的id's 当用户注册到系统中时,国家/地区的id作为外键保存在名为country /地区的列中。

现在我想做的是计算有多少个国家的用户注册了,例如 3 个用户从美国注册,它会显示国家的名称以及有多少用户从这个国家注册,比如United States: 3等等, 仅适用于用户注册的国家。

这是我的架构:

用户表

在此处输入图像描述

国家表:

在此处输入图像描述

这是我尝试过的方法,但是我无法理解如何使其正常工作:

<?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.

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