从db计算唯一用户

时间:2011-05-18 18:09:14

标签: mysql

我的db(MySQL)中有以下表结构:

id  group_id    item_id     project_id  user_id

用户可以拥有同一项目的多个条目。如何计算具有特定项目的唯一用户(减去项目所有者ID)?

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

这看起来不对,但我不相信我得到了正确的结果。我错过了什么吗?

4 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:2)

将DISTINCT添加到您的COUNT并消除GROUP BY。

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

答案 2 :(得分:1)

您不需要GROUP BY条款。

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

如果要在同一查询中列出每个组的成员数,可以使用GROUP BY project_id:

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

通过像现在一样对user_id进行分组,结果集中的每一行都将包含1

答案 3 :(得分:1)

尝试区分?

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