Retrieving COUNT of a calculated expression
I read here that I can include an argument inside COUNT, to return a calculated value. I'm trying the following but I'm missing something. Ca开发者_如何学JAVAn you help? Thanks!
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']; }
Try
"SELECT
COUNT(*) AS completed
FROM " .SESSIONDB. "
WHERE client = '$client' AND page_max > 126
AND page = 'interaction.php'"
How about this
SELECT
SUM(CASE WHEN page_max > 126 THEN 1 ELSE 0 END) AS completed
FROM table
WHERE client = '$client'
AND page = 'interaction.php'
Or as Nicolò Martini said, move page_max to WHERE condition if you don't need total count of items.
This should do what you want:
SELECT COUNT(IF(page_max>126,1,NULL)) AS completed ....
COUNT
counts the number of rows that aren't NULL
. This expression turns anything where page_max is greater than 126 into 1
and anything that isn't into NULL
.
That said, why not just move page_max
to the WHERE
condition?
精彩评论