簡體   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