0

I have these 3 tables

users [ id , username, password ]
logs [ id, user_id, action ]
user_propeties [ id, user_id, prop_name, prop_value ]

I want to select All the user's columns with the Count(logs.id) and count(user_propeties.id) Only where prop_value IS NULL from the 2 tables depending on the user id

I have the following query

SELECT t1.*, count(t2.`id`) as total_logs,count(t3.`id`) as total_propeties
                       FROM `users` t1
                       LEFT JOIN `user_propeties` t2
                                ON t1.`id` = t2.`user_id` AND ISNULL(t2.`prop_value`)
                       LEFT JOIN `logs` t3
                                ON t3.`user_id` = t1.`id`                                       
                       GROUP BY t1.id
                       ORDER BY t1.id DESC

Which returns rows but with wrong count value. What i am doing wrong? Thank you

1 Answer 1

1

I suspect you want some DISTINCT with that, otherwise it will return the count of all combinations of logs and properties;

SELECT t1.*, COUNT(DISTINCT t2.`id`) as total_logs,
             COUNT(DISTINCT t3.`id`) as total_propeties
FROM `users` t1
LEFT JOIN `user_propeties` t2
         ON t1.`id` = t2.`user_id` AND ISNULL(t2.`prop_value`)
LEFT JOIN `logs` t3
         ON t3.`user_id` = t1.`id`                                       
GROUP BY t1.id
ORDER BY t1.id DESC
Sign up to request clarification or add additional context in comments.

2 Comments

It worked but i can't get it why. Can you explain me?
If you have multiple properties and multiple logs, each id may be returned more than once, so a regular COUNT will count all duplicates. COUNT DISTINCT will only count each id once, so if log#4 is returned twice, it will still only be counted once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.