Paul
Paul

Reputation: 11746

Can I get two counts from mysql with a conditional where statement?

I'm currently getting a users visit count based on a timestamp but I would also like to include the total number of visits. Is this possible to do with one MySQL statement. Here is my current query that returns only one count based on a timestamp:

$sql = "SELECT count(*) as visitors_count FROM profile_visits
        LEFT JOIN users on users.user_id=profile_visits.user_id
        LEFT JOIN profile_info ON profile_info.user_id = users.user_id
        WHERE profile_user_id=5
        AND users.restricted <> 1
        AND profile_visits.visit_time > '2012-07-30 18:53:16'";

Can I also return the total number of visits that exclude the timestamp?

Upvotes: 1

Views: 126

Answers (1)

Zane Bien
Zane Bien

Reputation: 23125

You can use a CASE expression to conditionally aggregate within COUNT():

SELECT    COUNT(*) AS total_count,
          COUNT(CASE WHEN profile_visits.visit_time > '2012-07-30 18:53:16' THEN 1 END) AS visitors_count
FROM      profile_visits
LEFT JOIN users ON users.user_id=profile_visits.user_id
LEFT JOIN profile_info ON profile_info.user_id = users.user_id
WHERE     profile_user_id=5 AND 
          users.restricted <> 1

I simply moved the > '2012-07-30 18:53:16' from the WHERE clause to the CASE expression within COUNT() which will only count the row if it meets that criteria. And of course COUNT(*) will count all rows regardless of the timestamp.

Upvotes: 2

Related Questions