MySQL:查找重复的用户WHERE项目计数< 1

时间:2011-02-13 15:57:06

标签: sql mysql

尝试通过电子邮件找到重复的用户,其项目数小于0.我已经让重复的用户工作(虽然它返回已排序的用户的完整列表,而不是子集):

select users.id, email, count(email) as count
from users
group by users.email
order by count desc

我正在尝试加入其中count(items.id)<的项目1,但这似乎不起作用。

select users.id, email, count(email) as count
from users
join items on items.user_id = users.id
having count(items.id) < 1
group by users.email
order by count desc

我也尝试过IN查询,但似乎无法正确使用语法。

简单的方法吗?谢谢!

更新

这个查询起到了作用:

    select DISTINCT(u1.id), u1.email
    from users u1
    inner join users u2
        on 1=1
        and u1.email = u2.email
        and u1.id != u2.id
    where not exists (select * from items i where i.user_id = u1.id)
    order by u1.id

2 个答案:

答案 0 :(得分:2)

重复用户:

select 
    email, 
    count(*) as count,
    min(id) first_user_with_this_email_id
from users
group by email
having count(*) > 1

对于第二个,试试这个:

select 
    users.email, 
    count(*) as count
from users
left join items 
on (items.user_id = users.id)
where items.id is null --there are no related items
group by users.email
having count(*) > 1 --there are at least two users

第二个版本的另一个版本:

select 
    u.email, 
    count(*) as count
from users u
where not exists (select * from items i where i.user_id = u.id)
group by u.email
having count(*) > 1 --there are at least two users

确保在items表中有user_id索引。

答案 1 :(得分:-1)

尝试使用WHERE而不是“having”。 可能此链接有助于:http://www.devx.com/DevX/Tip/21295

修改后的查询将是:

select users.id, email, count(email) as count
from users
join items on items.user_id = users.id
where count(items.id) < 1
group by users.email
order by count desc

[没有运行并检查查询,只是更正]