簡體   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