MySql查询,计算user_id的出现次数

时间:2014-02-14 16:58:20

标签: php mysql

我的查询是:

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

我的结果是:

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

我需要得到每个人的计数:

4> 2

5> 2

6> 1

我尝试了多种子查询或使用不同的查询,但我迷路了但是我没有达到目标......

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

添加分组即可。

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

答案 1 :(得分:1)

您可以使用GROUP BYCOUNT来实现此目的。不需要子查询。

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

答案 2 :(得分:1)

您不需要使用子查询执行此操作:

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;

我的猜测是,你真的想要:

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;

对于没有目标的用户,这将返回0。第一个将为他们返回1