【问题标题】:SQL where clause to check if all selected column value is in a subquery selectSQL where 子句检查所有选定的列值是否在子查询中
【发布时间】:2019-09-26 06:24:14
【问题描述】:

下面的select概念可以翻译成sql select吗?

select S_ID from table1 where S_Type = TYPE and all S_ID in (select S_ID from table2)

这个概念如下:

item1、item2 和 item3 都应该在(从表中选择项目)

如果所有 S_ID 都在其中(从 table2 中选择 S_ID),则 select 语句应该只返回一行/s

【问题讨论】:

  • 您能分享一些存在于 S_ID 列中的数据吗?
  • 我不清楚。如果所有S_ID 都不包含在table2 中会怎样?
  • @TimBiegeleisen - 请查看我更新的问题
  • @onhax 。 . .这是没有意义的。为什么不从第二个表中选择s_id?什么是item_1 等?它们不在查询中。
  • 我认为我们肯定需要表和预期输出的样本数据。我无法决定您是想要一个简单的内部连接,还是想要一个基于整个行子集的复杂比较。

标签: sql sql-server


【解决方案1】:

如果您希望S_IDs 的所有items 都在第二个表中,则使用聚合

select t1.S_ID
from table1 t1
where t1.S_Type = 'TYPE' and
      t1.item in (select t2.item from table2 t2)
group by S_ID
having count(distinct t1.item) = (select count(distinct t2.item) from table2 t2);

【讨论】:

    【解决方案2】:

    你需要把比较运算符然后全部

    select S_ID from table1 where S_ID = ALL (select S_ID from table2)
    

    【讨论】:

    • 感谢您的回复。将对此进行测试并在一分钟内返回
    猜你喜欢
    • 2022-01-17
    • 1970-01-01
    • 2011-12-03
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多