2014-01-24 36 views
0

表和有關(列):從另一個表之間沒有聯繫SQL選擇數據/列

Attachment (att_id) 

Assignment (att_id, ctg_id, and itm_id) 

我已經嘗試了幾個小時,試圖叫我找的,而是利用數據。我無法弄清楚它背後的邏輯,看起來很簡單。

我需要調用的所有行的附件表,其中att_id 鏈接到ctg_id itm_id在分配表。

我在att_id = att_id上建立連接,但是當我需要恰好相反的連接時,會彈出附件表中所有連接到ctg_id或itm_id的的行。

非常令人沮喪。任何意見/幫助非常感謝。

回答

3

這應該選擇附件中的所有行,這些行在賦值中未由att_id引用。

SELECT * 
FROM Attachment 
WHERE att_id NOT IN (SELECT att_id FROM Assignment) 

JOIN通常用於查找鏈接,而不是查找非鏈接。 WHERE x NOT IN([blah])用於查找缺失的鏈接。

+0

哇,現在我感到無助!如上所述那樣工作。我想反過來做我想!感謝它背後的邏輯,我將注意未來。 –

2

一個LEFT OUTER JOIN是找到非匹配一個簡單的方法:

select at.* 
from Attachment at 
left outer join Assignment as on at.att_id = as.att_id 
where as.att_id is null 
+0

這也適用!感謝您向我展示執行此調用的不同方式背後的更多邏輯! –

0
select * from attachment a 
left join assignment a2 
where a2.ctg_id is null or a2.itm_id is null 
0

你可能想嘗試一個備用只是讓相關聯的子查詢不減慢你的速度。

create table Attachment (att_id int) 
create table Assignment (att_id int, ctg_id int, itm_id int) 
insert into Attachment values(100) 
insert into Attachment values(350) 
insert into Attachment values(7) 
insert into Attachment values(99) 

insert into Assignment values (100,1,1) 
insert into Assignment values (7,2,2) 

--SELECT * 
--FROM Attachment 
--WHERE att_id NOT IN (SELECT att_id FROM Assignment) 

SELECT ATT.* 
FROM Attachment ATT LEFT outer join Assignment ASI on ATT.att_id = ASI.att_id 
WHERE ISNULL(ASI.att_id,-1)=-1 

drop table Attachment 
drop table assignment 

編輯:大聲笑 - 當我打字時,還有兩個相同的答案進來。哦,好吧。

1

你想要什麼叫做Left Anti Semi Join

SELECT * 
FROM Attachment 
WHERE NOT EXISTS (SELECT 1 
        FROM Assignment 
        WHERE Attachment.att_id = Assignment.att_id) 

它比使用常規左外部連接更有效率,儘管SQL服務器通常足夠聰明以解決這個問題。

相關問題