Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL: query should return rows with count 0
    primarykey
    data
    text
    <p>I have 2 tables - User and Department and query that returns a count of users by departments. If user don't have department that returns "No department". But I needs to get also <strong>departments without user</strong> as count <strong>0</strong>. This is my query:</p> <pre><code>SELECT COALESCE(departments.name, 'No department') AS name, count( * ) AS count FROM users LEFT JOIN departments ON departments.id = users.department_id WHERE users.is_deleted = 0 AND users.company_id = 1 AND (TIMESTAMPDIFF(YEAR, `date_of_birth`, CURDATE()) BETWEEN 1 AND 18 ) GROUP BY departments.name </code></pre> <p>It should like this:</p> <pre><code>________________________ Dep name | count | ________________________ Dep 1 | 2 | ________________________ Dep 2 | 3 | ________________________ Dep 3 | 0 | if users in this department not exist ________________________ No dep | 1 | if users not have department ________________________ </code></pre> <p>Help me, please, guys!</p> <p>I found the solution </p> <pre><code>SELECT COALESCE(locations.name, 'Without location') AS location, COUNT(IF(TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()) BETWEEN 1 AND 17, 1, NULL)) 'group_1_17' FROM users LEFT JOIN locations ON locations.id = users.location_id WHERE users.is_deleted = 0 AND users.company_id = :company_id GROUP BY locations.name UNION SELECT locations.name AS location, 0 'group_1_17' FROM users RIGHT JOIN locations ON locations.id = users.location_id WHERE locations.company_id = :company_id AND users.id IS NULL" </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload