开发者

Count unique users from db

I have the following table structure in my db (MySQL):

id  group_id    item_id     project_id  user_id

Users can have multiple entrie开发者_Python百科s withing the same project. How do I count unique users withing a particular project (minus project owner id)?

SELECT COUNT(user_id) AS cnt
       FROM myTable
       WHERE project_id = $myProject
       AND user_id != 3
       GROUP BY user_id

This looks right but I don't believe I'm getting the right results. Am I missing something?


Select Count(Distinct user_id)
From MyTable
Where project_id = $myProject
    And user_id != 3


Add DISTINCT to your COUNT and eliminate the GROUP BY.

SELECT COUNT(DISTINCT user_id) AS cnt
   FROM myTable
   WHERE project_id = $myProject
   AND user_id != 3


You don't need a GROUP BY clause for this.

SELECT COUNT(DISTINCT user_id) AS cnt
FROM myTable
WHERE project_id = $myProject
  AND user_id != 3;

If you want to list the member count for each group in the same query, you can GROUP BY project_id:

SELECT COUNT(DISTINCT user_id) AS cnt
FROM myTable
GROUP BY project_id;

By grouping on user_id as you do now, every row in the resultset will contain 1.


Try Distinct?

SELECT DISTINCT COUNT(user_id) AS cnt FROM myTable WHERE project_id = $myProject AND user_id != 3
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜