简体   繁体   中英

Select with Multiple Counts on Left Join on Same Table

I'm not certain that this can be done, I have a table of users with a related table of user activity joined on a foreign key. Activity has different types, eg comment, like etc. I need to get users filtered by the number of each different type of activity.

What I have so far is this:

SELECT
      users.*, 
      COUNT(t1.id) AS comments, 
      COUNT(t2.id) AS likes
FROM users
     LEFT JOIN activity AS t1 ON users.id = t1.user_id
     LEFT JOIN activity AS t2 ON users.id = t2.user_id
WHERE t1.activity_type_id = 1 AND t2.activity_type_id = 2
GROUP BY users.id
HAVING comments >= 5 AND likes >= 5

This seems to be close but it's returning a user with a count of 5 both likes and comments, when in reality the user has 5 likes and 1 comment.

To be clear I want this query to return users who have 5 or more likes and also users who have 5 or more comments.

UPDATE:

I've created an SQL Fiddle. In this case I have 3 users:

  • User 1: 6 comments, 8 likes
  • User 2: 3 comments, 2 likes
  • User 3: 5 comments, 2 likes

I want the query to return only user 1 and 3, with their respective totals of likes and comments.

http://sqlfiddle.com/#!2/dcc63/4

You can use conditional summing to do the count and due to the way MySQL treats boolean expressions an expression like sum(case when et.name = 'comment' then 1 else 0 end) (the "normal" SQL syntax) can be reduced to sum(case when et.name = 'comment') .

SELECT
  u.id, 
  sum(et.name = 'comment') AS comments, 
  sum(et.name = 'like') AS likes
FROM users AS u
LEFT JOIN engagements AS  e ON u.id = e.user_id
JOIN engagement_types AS et ON e.engagement_type_id = et.id
GROUP BY u.id 
HAVING sum(et.name = 'comment') >= 5 
    OR sum(et.name = 'like') >= 5

Result:

| ID | COMMENTS | LIKES |
|----|----------|-------|
|  1 |        6 |     8 |
|  3 |        5 |     2 |

Sample SQL Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM