简体   繁体   中英

MySql query, counting occurrences of user_id

My query is:

SELECT * FROM (SELECT user_id
FROM goals
LEFT JOIN goal_results ON goals.id = goal_results.goal_id
WHERE goals.enabled = 1 AND validation = 'accepted') AS u

My results are:

| user_id |
| 4 |
| 5 |
| 4 |
| 5 |
| 6 |

I need to get the count of each of them like:

4 > 2

5 > 2

6 > 1

I've tried many kind of queries with subqueries or using distinct but I'm lost and I don't reach my goal.

Adding group by will do.

SELECT u.user_id, count(*) FROM (SELECT user_id
FROM goals
LEFT JOIN goal_results ON goals.id = goal_results.goal_id
WHERE goals.enabled = 1 AND validation = 'accepted') AS u
group by u.user_id

You can achieve this by using GROUP BY and COUNT . The subquery is not needed.

SELECT goal_results.user_id, COUNT(*) qty
FROM goals
LEFT JOIN goal_results ON goals.id = goal_results.goal_id
WHERE goals.enabled = 1 AND goal_results.validation = 'accepted'
GROUP BY goal_results.user_id

You don't need to do this with a subquery:

SELECT g.user_id, count(*)
FROM goals g LEFT JOIN
     goal_results gr
     ON g.id = gr.goal_id
WHERE g.enabled = 1 AND validation = 'accepted'
GROUP BY g.user_id;

My guess, though, is that you really want:

SELECT g.user_id, count(gr.goal_id)
FROM goals g LEFT JOIN
     goal_results gr
     ON g.id = gr.goal_id
WHERE g.enabled = 1 AND validation = 'accepted'
GROUP BY g.user_id;

This will return 0 for users that have no goals. The first will return 1 for them.

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