Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LEFT JOIN to get a count returns a zero count when no data in main table

I am trying to get a count of apps for a user, using LEFT JOIN. It needs to return users regardless of whether they have apps, but the query is returning an empty record with 0 apps when no users are present.

SELECT u.*, COUNT(a.id) AS apps_working  
FROM users u 
LEFT JOIN apps a ON (u.id = a.user_id)
WHERE u.company_id = :company_id 
AND u.account_type = 3

EDIT: When there are no users present, the results look like this:

Array
(
[0] => Array
    (
        [id] => 
        [company_id] => 
        [user_login] => 
        [user_password] => 
        [first_name] => 
        [last_name] => 
        [user_hash] => 
        [user_slug] => 
        [date_joined] => 
        [last_login] => 
        [account_type] => 
        [status] => 
        [apps_working] => 0
    )

)
like image 586
Judson Avatar asked Feb 27 '26 08:02

Judson


1 Answers

This is a query that is ALWAYS going to return a value because count(*) will always return something. If you don't want to see that, add a case statement to trap 0 and return null.

like image 134
T Gray Avatar answered Mar 02 '26 00:03

T Gray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!