Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL query that returns active users with no headset

I have 4 tables:

Table user with id, email, first_name, last_name, country, activated
Table assets with id, serial, model_id, assigned_to
Table models with id, name, category_id
Table categories with id, name
Table status_labels with id, name

& I want to know active people that have no headset, I tested a query but returns me nothing, because a user can have a laptop or desktop and monitor, etc. which means assets should not be null

Here is my query:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT u.id, u.email, u.first_name, u.last_name
FROM users u
WHERE u.activated = 1 AND u.country = 'MA' AND u.id NOT IN (
    SELECT assigned_to
    FROM assets a
    INNER JOIN models m ON a.model_id = m.id
    INNER JOIN categories c ON m.category_id = c.id
    WHERE c.name = 'Desktop'
)

Here is another one: it returns also nothing

SELECT u.id, u.email, u.first_name, u.last_name
FROM users u
LEFT JOIN assets a ON a.assigned_to = u.id
LEFT JOIN models m ON m.id = a.model_id
LEFT JOIN categories c ON c.id = m.category_id
WHERE u.activated = 1 AND u.country = 'MA' AND c.name = 'Headset' AND a.id IS NULL;

I’m expecting values in return

>Solution :

You could aggregate by user and then assert that the headset count be zero:

SELECT u.id, u.email, u.first_name, u.last_name
FROM users u
LEFT JOIN assets a ON a.assigned_to = u.id
LEFT JOIN models m ON m.id = a.model_id
LEFT JOIN categories c ON c.id = m.category_id
WHERE u.activated = 1 AND u.country = 'MA'
GROUP BY u.id, u.email, u.first_name, u.last_name
HAVING SUM(c.name = 'Headset') = 0;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading