SQL 查询(需要自连接?)

SQL query (self-join needed?)

我有一个包含多个字段和两个 i.d 字段的 table,一个字段称为 regular_id,第二个字段称为特殊字段。

每行可以在 regular_id 和 special_id 下有一个值,如果在 special_id 下有一个值,那么它作为 table 中的其他地方存在=21=]。

我想构建一个查询 -

给我所有 special_id 字段为空的行,但 regular_id 字段中的值在其他任何地方(在任何其他 row/record 中都不存在 table 在特殊字段下。

注意:未经测试。

select A.*
from table A
where A.special_id is null
and not exists (select 1 from table B where B.special_id = A.regular_id)

当然 A 和 B 是同一个数据库的别名 table。

子查询或者exist都可以。

这与 Oracle 中著名的 scott.EMP table 非常相似。

create table emp(  
  empno    number(4,0),  
  ename    varchar2(10),  
  job      varchar2(9),  
  mgr      number(4,0),  
  hiredate date,  
  sal      number(7,2),  
  comm     number(7,2),  
  deptno   number(2,0),  
  constraint pk_emp primary key (empno),  
  constraint fk_deptno foreign key (deptno) references dept (deptno)  
)

所以你问题中的 regular_id 是 scott.EMP table 中的 empno(员工 ID),special_id 是 mgr(经理 ID)

现在您的问题转换为 scott.EMP: 其中 mgr 字段为空,但 empno 字段中的值在 mgr 字段下的那个 table 中的其他任何地方(在任何其他 row/record 中都不存在。

select m.*
from scott.EMP m
where m.mgr IS NULL
and m.empno not in (select mgr from scott.EMP where mgr is not null)

感谢Thorsten Kettner的指正,时刻注意列表中的NULL

您的问题翻译成自然语言: The person who has no manager and is not manager of any employee.

自联接是正确的方法。

SELECT a.special_id, a.regular_id
FROM tablename  a
LEFT JOIN tablename b
    ON a.regular_id = b.special_id 
WHERE a.special_id IS NULL
AND b.special_id IS NULL;

注意:将 tablename 替换为您的实际 table 名称。

示例数据:

REGULAR_ID  SPECIAL_ID
1           1
1           2
2           1
3           1
1           NULL
3           NULL

结果:

REGULAR_ID  SPECIAL_ID
3           NULL