繁体   English   中英

SQL查询(需要自我连接吗?)

[英]SQL query (self-join needed?)

我有一个包含多个字段和两个id字段的表,一个字段称为normal_id,第二个字段称为special。

每行都可以在regular_id和special_id下有一个值,如果在special_id下有一个值,则它在表中的其他地方作为regular_id存在。

我想建立一个查询,说-

给我提供special_id字段为null的所有行,但是normal_id字段中的值在该特殊字段下的该表中的其他任何地方(在任何其他行/记录中)都不存在。

注意:未经测试。

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是同一数据库表的别名。

子查询还是可以存在的。

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

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表中的empno(员工ID),而special_id是mgr(经理ID)

现在,您的问题转换为scott.EMP:其中mgr字段为null,但是empno字段中的值在该表中的mgr字段下的其他任何地方(在任何其他行/记录中)都不存在。

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;

注意:用实际的表名替换表名。

样本数据:

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

结果:

REGULAR_ID  SPECIAL_ID
3           NULL

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM