【问题标题】:Select by an IN clause but should behave like AND [duplicate]按 IN 子句选择,但行为应类似于 AND [重复]
【发布时间】:2014-02-23 19:20:00
【问题描述】:

IN 子句的作用类似于OR

select from table where id in (1, 2, 3)

在组中的任何项目匹配时选择(如果 id 为 1、2 或 3,则返回)。


我需要类似的东西,但基于两列,只有当ColumnA 具有ColumnB 的所有值时它才应该返回。

例如,

  ColumnA         ColumnB
---------------------------
    1               a
    2               b
    3               c

    1               a
    1               b
    1               c


select CoumnA from table where CoumnA in every ColumnB of (a, b, c);
 -> 1 --since only 1 has all a, b and c

select CoumnA from table where CoumnA in every ColumnB of (b);
 -> 1 --since 1 has b
 -> 2 --since 2 has b

等等。我知道in every of 不是一个合适的关键字,我只是想展示一个例子。

我无法尝试任何事情,因为我无法理解这个逻辑。

【问题讨论】:

  • @Rikesh 谢谢,我会看到的。有时对于 sql 类型的问题几乎不可能搜索重复项。

标签: mysql sql select in-clause


【解决方案1】:

这个呢:

select t1.ColumnA from table t1 where 
exists (select * from table t2 where t1.ColumnA=t2.ColumnA and t2.ColumnB='a')
and exists (select * from table t2 where t1.ColumnA=t2.ColumnA and t2.ColumnB='b')
and exists (select * from table t2 where t1.ColumnA=t2.ColumnA and t2.ColumnB='c')
group by t1.ColumnA

【讨论】:

    【解决方案2】:

    尝试只使用IN(a,b,c) 按具有count(distinct id) = 3 的ID 分组。

    【讨论】:

      猜你喜欢
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-04
      • 2014-06-24
      • 2014-10-03
      相关资源
      最近更新 更多