SQL 查询如何确保只有列表中的条件在 table

SQL query how do I make sure only the criteria in a list are in a table

我正在尝试执行查询,我想确保只有使用与查询相关的列表的条件在 table 中。 这是一个例子table

table1
field1|field2
-------------
1     | 2
1     | 3
1     | 4

select * from table1 
where field1 = 1 
and field2 in(2,3)

这将 return 前 2 条记录,但我想做的是测试并查看这些是否是 field1 是其中的唯一记录。在这种情况下,我想要一个以某种方式 return 对我来说是错误结果的查询。

您可以比较总行数 where field1 is 1 和行数 where field1 is 1 and field 2 is (2,3)。如果值匹配则其 TRUE 否则 FALSE

Setup:

SELECT * INTO #TBLA FROM (
select 1 field1, 2 field2 UNION ALL
select 1 field1, 3 field2 UNION ALL
select 1 field1, 4 field2 ) A

Query: 
SELECT CASE 
    WHEN COUNT(*) - 
        COUNT(CASE WHEN field2 IN (2,3)
                    THEN 1
                END) > 0
        THEN 'false'
    ELSE 'true'
    END FIELD1CNT
FROM #TBLA
WHERE field1 = 1

所以您想要所有 field1 值在 (2,3) 中有一个 field2 值并且没有其他值?只需添加一个 NOT EXISTS:

select * from table1 
where field1 = 1 
and field2 in(2,3)
and NOT EXISTS
  (
   SELECT null
   FROM table1
   where field1 = 1 
   and field2 NOT in (2,3)
   )