I'm using MySql 5.5.37. I have a query meant to count the number of times a user logged in
select u.id, IFNULL(count(*), 0)
FROM user u left join logins l
on u.id = l.user_id group by u.id;
The problem is, if a user has never logged in, the above is still returning a count of one for that user, probably because the LEFT JOIN returns a NULL when there isn't a matching row. How do I change this so that I get zero if the user has never logged in, and then the appropriate count if they have logged in at least once?
Here's the simplest way to count NULL values in SQL The easiest way to count the NULLs in a column is to combine COUNT(*) with WHERE <column name> IS NULL . This is a common and fundamental data quality check.
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.
The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.
LEFT JOIN , also called LEFT OUTER JOIN , returns all records from the left (first) table and the matched records from the right (second) table. If there is no match for a specific record, you'll get NULLs in the corresponding columns of the right table.
You can use count on one of the columns of right table.
select u.id,
count(l.user_id)
from user u
left join logins l on u.id = l.user_id
group by u.id
In left joint when the user had never logged in l.user_id = null
in the result so try this should work :
select
u.id,
sum(if(l.user_id is not null,1,0))
FROM user u left join logins l on u.id = l.user_id group by u.id;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With