我有一个带有名称的表users
和一个名为source
. 该列包含 3 种不同类型的值,它们是字符串(facebook、google、yahoo)。现在我需要计算该列中有多少 Facebook 字符串、google 字符串和 yahoo 字符串。
使用php查询有什么简单的方法吗?
我如何才能显示数字!!!!!!!!!!
您可以使用此解决方案。这会将计数放入单独的列中,因此您可以轻松地引用 php 中不同字符串的计数:
SELECT
COUNT(CASE WHEN source = 'facebook' THEN 1 END) AS facebook_count,
COUNT(CASE WHEN source = 'google' THEN 1 END) AS google_count,
COUNT(CASE WHEN source = 'yahoo' THEN 1 END) AS yahoo_count
FROM
users
编辑:根据您对此答案的评论...关于如何使用 php 检索这些值,如下所示:
$sql = "
SELECT
COUNT(CASE WHEN source = 'facebook' THEN 1 END) AS facebook_count,
COUNT(CASE WHEN source = 'google' THEN 1 END) AS google_count,
COUNT(CASE WHEN source = 'yahoo' THEN 1 END) AS yahoo_count
FROM
users";
$social = mysql_query($sql);
while($row = mysql_fetch_assoc($social))
{
echo "FB Count: {$row['facebook_count']}" . '<br />';
echo "Google Count: {$row['google_count']}" . '<br />';
echo "Yahoo Count: {$row['yahoo_count']}";
}
试试这个:
Select source, count(1) from users where source like 'facebook'
select source, count(source) from users group by source
如果您的source
列不是可选字段,那么您可以像这样简单地使用,
select source as source_name, count(*) as counts from users group by source
否则你可以使用like,
select source as source_name, count(source) as counts from users group by source