mysql and or 代替 in_MySQL中是否有类似IN的东西,但是使用AND而不是OR?

bd96500e110b49cbb3cd949968f18be7.png

I need a SQL statement to retrieve records where it key (or any column) is in a associate table, for example:

documentId termId

4 1

4 2

3 3

5 1

This:

SELECT documentId

FROM table

WHERE termId IN (1,2,3)

...will retrieve any documentid value where the termid value is 1 or 2 or 3.

Is there something like this but return documentid values where the termid values are 1 and 2 and 3? Like an IN but with AND.

解决方案

There's no straight forward functionality, but there are two options:

Using GROUP BY/HAVING

SELECT t.documentid

FROM TABLE t

WHERE t.termid IN (1,2,3)

GROUP BY t.documentid

HAVING COUNT(DISINCT t.termid) = 3

The caveat is that you have to use HAVING COUNT(DISTINCT because duplicates of termid being 2 for the same documentid would be a false positive. And the COUNT has to equal the number of termid values in the IN clause.

Using JOINs

SELECT t.documentid

FROM TABLE t

JOIN TABLE x ON x.termid = t.termid

AND x.termid = 1

JOIN TABLE y ON y.termid = t.termid

AND y.termid = 2

JOIN TABLE z ON z.termid = t.termid

AND z.termid = 3

But this one can be a pain for handling criteria that changes a lot.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值