MySQL LEFT JOIN返回重复的结果

时间:2013-11-14 20:51:39

标签: mysql sql duplicates left-join duplicate-removal

我正在运行查询以查找已从我们的组织接收过服务的用户,但我不希望他们的用户ID被复制。例如,我可能在系统中有用户ID 1 5次,但我只希望他们的id计为1次。这是我的疑问:

mysql_query("SELECT COUNT(*) AS 'total'
FROM services
LEFT JOIN users
ON (services.USR_id = users.USR_id)
LEFT JOIN service_type
ON (services.SRV_type = service_type.TYPE_id)
WHERE services.MGR_orgid = $mgrorgid GROUP BY services.USR_id");

2 个答案:

答案 0 :(得分:1)

删除group by ...,然后将count(*)更改为count(distinct usr_id)

答案 1 :(得分:0)

SELECT COUNT(*) AS total FROM users u
WHERE EXISTS (
    SELECT * FROM services s
    WHERE s.USR_id = u.USR_id
    AND s.MGR_orgid = $mgrorgid
)

试试这个。我删除了包含service_type的部分,因为您在原始查询中对该表一无所知。