从DB中的列计算不同的no:字符串

时间:2012-07-09 08:10:20

标签: php mysql

我的表名为users,其中的列名为source。该列包含3种不同类型的值,即字符串(facebook,google,yahoo)。现在我需要计算有多少Facebook字符串,google字符串和&雅虎字符串出现在该列中。

使用php查询做任何简单的简单方法吗?

如何显示号码!!!!!!!!

4 个答案:

答案 0 :(得分:1)

您可以使用此解决方案。这会将计数分成不同的列,这样您就可以轻松地在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']}";
}

答案 1 :(得分:0)

试试这个:

 Select source, count(1) from users where source like 'facebook'

答案 2 :(得分:0)

select source, count(source) from users group by source

答案 3 :(得分:0)

如果您的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