我有一个MySQL数据库,其中包含用户的国家以及他们是个人还是组织。字段名称为'country‘和'type’。
使用PHP,我想‘计算’数据库中的国家数量、个人数量和组织数量,然后以以下示例格式显示这些数字:
<p>So far, <strong>500</strong> individuals and <strong>210</strong> organisations from <strong>40</strong> countries have registered their support.</p>如果有帮助,我现在使用下面的代码列出记录的总数:
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $link);
$result = mysql_query("SELECT * FROM table_name", $link);
$num_rows = mysql_num_rows($result);
echo " $num_rows\n ";
?>我的PHP / MySQL技能非常有限,所以我真的很难做到这一点。
首先要感谢大家!
本
发布于 2011-03-25 22:05:20
您要查找的是基于分组的计数。尝试如下所示:
$sql = "SELECT type, count(*) as cnt FROM users GROUP BY type";
$result = mysql_query($sql);
$counts = array();
while ($row = mysql_fetch_assoc($result)) {
$counts[$row['type']] = $row['cnt'];
}这将为您提供如下所示的数组
Array (
'individual' => 500,
'organization' => 210
)要计算国家/地区,请使用第一条语句作为posted by Hammerite。
EDIT__:添加了一个统计国家的详细示例
$sql = "SELECT COUNT(DISTINCT country) AS NumCountries FROM users";
$result = mysql_query($sql);
$number_of_countries = 0;
if ($row = mysql_fetch_assoc($result)) {
$number_of_countries = $row['NumCountries'];
}这样你就可以打印出来了:
printf('<p>So far, <strong>%d</strong> individuals and <strong>%d</strong> '.
'organisations from <strong>%d</strong> countries have registered '.
'their support.</p>', $counts['individual'], $counts['organization'],
$number_of_countries);发布于 2011-03-25 22:02:37
获取国家/地区数量:
SELECT COUNT(DISTINCT country) AS NumCountries FROM tableName要获取个人数量或组织数量,请执行以下操作:
SELECT COUNT(*) AS NumIndividuals FROM tableName WHERE type = 'individual'
SELECT COUNT(*) AS NumOrganisations FROM tableName WHERE type = 'organisation'发布于 2011-03-25 22:04:05
答案是使用SQL中的COUNT(*)函数检索答案:
SELECT COUNT(*) AS individual_count FROM user WHERE type = 'individual';
SELECT COUNT(*) AS organization_count FROM user WHERE type = 'organization';
SELECT COUNT(*) AS country_count FROM user GROUP BY country;最后一个将按国家/地区名称对查询集进行分组,每个国家/地区将占一行。对此结果集使用COUNT将给出不同国家的计数。
然后你可以通过在你的$result上使用mysql_fetch_assoc从mysql_query获取这个值,答案将包含在每个查询的‘invididual’,'organization_count‘和'country_count’中。
https://stackoverflow.com/questions/5433387
复制相似问题