0

I have some related tables

USERS

+----+--------------------------+------------+
| id | email                    | first_name |
+----+--------------------------+------------+
|  2 | [email protected] | Loren      |
|  3 | [email protected]    | Fernando   |
|  4 | [email protected]          | Evelyn     |
+----+--------------------------+------------+

EVENTS

+----+------------+
| id | name       |
+----+------------+
|  1 | Dolores ve |
|  2 | Harum erro |
|  3 | Ratione qu |
+----+------------+

EVENT_USER (join)

+---------+----------+
| user_id | event_id |
+---------+----------+
|       1 |        3 |
|       1 |       13 |
|       1 |       48 |
+---------+----------+

along with other tables related to user ( messages, connections ) etc

I want to get a count of messages, connections and other related data for users of a specific event

SQL I've tried:

SELECT u.`id`, u.`first_name`, u.`last_name`, 
COUNT(m.`id`) as message_count,
COUNT(a.`id`) as article_count
FROM `users` u
LEFT JOIN `event_user` eu ON u.`id` = eu.`user_id`
LEFT JOIN `messages` m ON u.`id` = m.`from`
LEFT JOIN `articles` a ON u.`id` = a.`user_id`
WHERE
eu.`event_id` = 3
GROUP BY u.`id`

But the counts are coming out to be same for both columns.

i.e. message_count and article_count are same for all users.

1
  • Could you please create a fiddle sqlfiddle.com with some sample data from all the tables ? Commented Oct 8, 2015 at 14:20

1 Answer 1

1

The easiest way to solve this is using count(distinct):

SELECT u.`id`, u.`first_name`, u.`last_name`, 
       COUNT(DISTINCT m.`id`) as message_count,
       COUNT(DISTINCT a.`id`) as article_count

If the values are large, then you might want to rewrite the query to aggregate before doing the joins.

The reason that you are getting the same values is that count(<column>) simply counts the number of non-null values. So, your query is saying that all users have both messages and articles (if one or the other were missing, the left joins would produce NULL values).

Sign up to request clarification or add additional context in comments.

1 Comment

This works. Im trying to wrap my head around the concept though.

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.