检索计算表达式的COUNT

时间:2011-10-10 07:20:16

标签: mysql

我读了here我可以在COUNT中包含一个参数,以返回一个计算值。我正在尝试以下但我错过了一些东西。你能帮我吗?谢谢!

  mysql_select_db(DATABASE_NAME, $connection);
    $client = "demo/";
    $result = mysql_query
    (
        "SELECT 
        COUNT(page_max > 126) AS completed 
        FROM " .SESSIONDB. " 
        WHERE client = '$client' 
        AND page = 'interaction.php'
        "
    ); 
    if(mysql_error()) die(DIRECTORY_TITLE . " - Error DBA110 " . mysql_error());
    // output THE QUERY
    while($row = mysql_fetch_assoc($result))
    {
        echo $row['completed'];
    }

3 个答案:

答案 0 :(得分:1)

尝试

 "SELECT 
    COUNT(*) AS completed 
    FROM " .SESSIONDB. " 
    WHERE client = '$client' AND page_max > 126
    AND page = 'interaction.php'"

答案 1 :(得分:1)

这个怎么样

SELECT 
SUM(CASE WHEN page_max > 126 THEN 1 ELSE 0 END) AS completed 
FROM table
WHERE client = '$client' 
AND page = 'interaction.php'

或者如NicolòMartini所说,如果您不需要项目的总数,请将page_max移至WHERE条件。

答案 2 :(得分:0)

这应该做你想要的:

SELECT COUNT(IF(page_max>126,1,NULL)) AS completed ....

COUNT计算不是NULL的行数。此表达式将page_max大于126的任何内容转换为1以及任何不属于NULL的内容。

那就是说,为什么不将page_max移到WHERE条件?