mysql中判断一列在另一列中没有,Mysql选择一列中具有相同值,另一列具有不同值的行...

I'd really appreciate it if someone could validate my SQL query.

For the following dataset:

MD5 UserPK CategoryPK

ADCDE 1 7

ADCDE 1 4

ADCDE 1 7

dffrf 1 7

dffrf 2 7

dffrf 2 6

dffrf 1 1

I'd like to select MD5 and CategoryPK where two or more rows exist with identical MD5 values, identical CatgegoryPK and two or more DIFFERENT UserPK values.

In other words, I'd like to know the MD5 and categoryPK of all records where two or more different users (UserPK) have assigned the same category (UserPK) to the same file (Md5). I'm not interested in records the same user has assigned the category to multiple times, (unless a different user has also assigned the same category to that file).

So from the above data, I would like to be returned just:

md5 CategoryPK

dffrf 7

The query I've written is:

SELECT md5,

count(md5),

count(distinct categorypk) as cntcat,

count(distinct userpk) as cntpk

FROM Hash

group by md5 having count(md5) > 1

and cntpk > 1

and cntcat = 1;

It seems to work, but before I start using it in anger, I'd appreciate a second opinion in case I've missed something or if there is a better way of doing it.

Thanks

解决方案

I don't think your code will give you what you're after; what happens when a file has been assigned more than one category by multiple users, with some categories overlapping? Then cntcat != 1, so your HAVING clause will fail to match even though the file has indeed been categorised the same way by multiple users.

I would instead use a self-join:

SELECT a.MD5, a.CategoryPK

FROM Hash a

JOIN Hash b

ON a.MD5 = b.MD5

AND a.UserPK <> b.UserPK

AND a.CategoryPK = b.CategoryPK

GROUP BY a.MD5, a.CategoryPK

HAVING COUNT(DISTINCT a.UserPK) > 2 -- you said "more than 2" ?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值