Select 与多个字段不存在于同一个 table

Select with not exist in the same table with multiple fields

我需要 select 来自 table 的注册,但不存在于同一个 table 中。我的意思是如果我有这个 table:

ID   VALUE1   VALUE2   VALUE3
1      1         1        1
2      2         2        1
3      3         4        1
4      1         5        1
5      2         2        2
6      3         4        2
7      1         8        2
8      2         2        2

查询结果应该是

ID   VALUE1   VALUE2   VALUE3
1      1         1        1
4      1         5        1

因为 value1 和 value2 的其余值相同,但 value3 不同。我的意思是 table 的第 2 行与第 5 行相同。

我尝试做类似但不起作用的事情:

select t1.value1, t1.value2 from table1 t1 where value3=1
and not exist 
(select t2.value1, t2.value2 from table2 t2 
where t1.value1=t2.value1 and t1.value2=t2.value2 and value3=2)

谢谢你的建议,对不起我的英语

您可以按如下方式使用NOT EXISTS

SELECT * 
  FROM YOUR_TABLE T1
 WHERE T1.VALUE3 = 1
   AND NOT EXISTS 
       (SELECT 1 
          FROM YOUR_TABLE T2
         WHERE T1.VALUE1 = T2.VALUE1
           AND T1.VALUE2 = T2.VALUE2)

我认为 not exists 可以满足您的要求:

select t1.*
from table1 t1
where t1.value3 = 1 and
      not exist (select 1
                 from table2 t2 
                 where t2.value1 = t1.value1 and
                       t2.value2 = t1.value2 and
                       t2.value3 = 2
                );

也就是说,您还可以使用 window 函数:

select t1.*
from (select t1.*,
             max(value3) over (partition by value1, value2) as max_value3
      from table1 t1
      where value3 in (1, 2)
     ) t1
where max_value3 = 1;

我认为您 exists 的方向是正确的。

我会这样表述您的查询:

select t1.* 
from table1 t1 
where 
    t1.value3 = 1
    and not exist (
        select 1 from table1 t2 
        where t1.value1 = t2.value1 and t1.value2 = t2.value2 and t2.value3 = 2
    )

要点:

  • exists 子查询应该是 from table1 (您的查询使用 table2 但似乎 table 实际上并不存在)

  • 您实际上不需要 exists 子查询中的 return 列,因为它所做的只是检查 某行 产生 - 因此 select 1