Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MySQL, how do I count zero if a LEFT JOIN doesn't match anything?

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?

like image 543
Dave Avatar asked Apr 04 '17 18:04

Dave


People also ask

How do I count NULL values in a SQL join?

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.

Can LEFT join have NULL values?

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.

How do I count 0 in SQL?

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.

How does LEFT join work with NULLs?

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.


2 Answers

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
like image 52
Gurwinder Singh Avatar answered Oct 07 '22 16:10

Gurwinder Singh


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;
like image 42
Charif DZ Avatar answered Oct 07 '22 15:10

Charif DZ