许多问题也被问到相同的问题。但是先听我说。
我有两个使用LEFT JOIN
连接的表,第一个表是用户表,第二个表只是引用表划分表
用户表
user_id | name | division_id
0 | ABC | 0
1 | DEF | 1
2 | GHI | 1
分区表
id | name | protect class
1 | div_1 | 1
我的原始查询
SELECT count(usr.user_id)
FROM user as usr
LEFT JOIN division as dv
ON dv.id = usr.division_id
WHERE
dv.protect_class != '1'
但是当我想选择不带分隔符的用户
SELECT count(usr.user_id)
FROM m_users as usr
LEFT JOIN m_division as dv
ON dv.id = usr.division_id OR usr.division_id = '0'
WHERE
dv.protect_class != '1'
事情有点怪异,不具有Division_id或等于0的用户将根据获得的除法条目数进行多次计数。
我也尝试添加独特的
SELECT distinct count(usr.user_id)
FROM m_users as usr
LEFT JOIN m_division as dv
ON dv.id = usr.division_id OR usr.division_id = '0'
WHERE
dv.protect_class != '1'
但是对我来说仍然没有运气。 当我查询这个
SELECT distinct usr.*
FROM m_users as usr
LEFT JOIN m_division as dv
ON dv.id = usr.division_id OR usr.division_id = '0'
WHERE
dv.protect_class != '1'
然后对它进行物理计数(手动),计数是正确的,那么如果我应用count()函数,则计数是错误的。所以我只想请教一下,
如何计算条目而不计算我的LEFT JOIN
中的重复项?
答案 0 :(得分:1)
您可以在下面尝试-count(distinct usr.user_id)
SELECT count(distinct usr.user_id)
FROM m_users as usr
LEFT JOIN m_division as dv
ON dv.id = usr.division_id OR usr.division_id = '0'
WHERE
dv.protect_class != '1'
答案 1 :(得分:0)
以“ OR”联接会在匹配条件时导致多次联接
SELECT count(usr.user_id)
FROM m_users as usr
LEFT JOIN m_division as dv
ON dv.id = usr.division_id
WHERE
dv.protect_class != '1'
and (usr.division_id = '0' OR usr.division_id IS NULL)