2010-11-18 75 views
0

的2存在的條件我有4個表:T1,T2,T3,T4。我需要顯示t1.event_id,t1.event_name,其中t1.event_id僅存在於3個表格(t2,t3,t4)中的2個表格中。我嘗試使用連接,但我所能做的只是返回所有表中存在的event_ids。如何加入4代表與數據只在3個表

這是DDL.sql。

CREATE TABLE t1 
(event_id  NUMBER(15) NOT NULL, 
event_name  VARCHAR2(80), 
CONSTRAINT pk_event PRIMARY KEY (event_id)); 

CREATE TABLE t2 
(eid  NUMBER(15) NOT NULL, 
equipment  VARCHAR2(100), 
CONSTRAINT fk_eid2 FOREIGN KEY (eid) 
REFERENCES t1 (event_id) ON DELETE CASCADE); 

CREATE TABLE t3 
(eid  NUMBER(15) NOT NULL, 
security  VARCHAR2(100), 
CONSTRAINT fk_eid3 FOREIGN KEY (eid) 
REFERENCES t1 (event_id) ON DELETE CASCADE); 

CREATE TABLE t4 
(eid  NUMBER(15) NOT NULL, 
setup_by  TIMESTAMP, 
CONSTRAINT fk_eid4 FOREIGN KEY (eid) 
REFERENCES t1 (event_id) ON DELETE CASCADE); 
+0

你需要3張桌子中的2張嗎?或者是僅存在於t2的情況,而不是t3或t4也是有效的? – Doug 2010-11-18 23:49:12

回答

0

如果您需要的3和表2,此查詢不會沒有一點邏輯工作...但如果你正在尋找三種關係中的一種缺失的情況,它會。但是,它應該讓你開始正好3個案例中的2個。

select t1.event_id, t1.event_name from t1 left outer join t2 on t1.event_id = t2.eid where t2.eid is null 
union 
select t1.event_id, t1.event_name from t1 left outer join t3 on t1.event_id = t3.eid where t3.eid is null 
union 
select t1.event_id, t1.event_name from t1 left outer join t4 on t1.event_id = t4.eid where t4.eid is null 

基本上,左外連接比較子表的id設置爲null會有效地讓你從每個表中缺少的行,然後你就可以聯合在一起的結果。如果要確保只有一個表中的數據缺失,則需要對每個子查詢上的其他兩個表執行內部連接,以確保其正常工作。喜歡的東西:

select t1.event_id, t1.event_name from t1 left outer join t2 on t1.event_id = t2.eid 
inner join t3 on t1.event_id = t3.eid inner join t4 on t1.event_id = t4.eid 
where t2.eid is null 
union 
select t1.event_id, t1.event_name from t1 left outer join t3 on t1.event_id = t3.eid 
inner join t2 on t1.event_id = t2.eid inner join t4 on t1.event_id = t4.eid 
where t3.eid is null 
union 
select t1.event_id, t1.event_name from t1 left outer join t4 on t1.event_id = t4.eid 
inner join t3 on t1.event_id = t3.eid inner join t2 on t1.event_id = t2.eid 
where t4.eid is null 
1

不幸的是,我沒有在時刻派上用場甲骨文的副本(或任何DB爲此事),但我首先想到的是LEFT OUTER JOIN每個表,然後通過過濾下來解碼每個表中的ID的存在?

SELECT t1.event_id, t1.event_name 
    FROM t1 
     LEFT OUTER JOIN t2 ON t1.event_id = t2.eid 
     LEFT OUTER JOIN t3 ON t1.event_id = t3.eid 
     LEFT OUTER JOIN t4 ON t1.event_id = t4.eid 
WHERE (
     DECODE(t2.eid, null, 0, 1) + 
     DECODE(t3.eid, null, 0, 1) + 
     DECODE(t4.eid, null, 0, 1) 
     ) >= 2