2016-01-14 28 views
0

我有3個表:SQL - 在另一臺(3臺關係)不存在選擇的記錄

Table_Cars 
-id_car 
-description 

Table_CarDocuments 
-id_car 
-id_documentType 
-path_to_document 

Table_DocumentTypes 
-id_documentType 
-description 

我想選擇做有4個特定id_documentType在桌子上Table_CarDocuments文檔中的所有汽車。

事情是這樣的:

Car1 | TaxDocument 
Car1 | KeyDocument 
Car2 | TaxDocument 

有了這個,我知道,我的思念CAR 1的2個文件和CAR2的1號文件。

+0

樣本數據和預期的結果幫助。你想要所有四個文件丟失嗎?或者,如果四個中的任何一個失蹤了,你想嗎? –

+0

想要爲每輛車丟失的每個文件得到1行 –

回答

2

您正在查找遺失的汽車文件。所以交叉加入汽車和文件類型,並尋找不在汽車表格中的組合。

select c.description as car, dt.description as doctype 
from table_cars c 
cross join table_documenttypes dt 
where (c.id_car, dt.id_documenttype) not in 
(
    select cd.id_car, cd.id_documenttype 
    from table_cardocuments cd 
); 

更新:它顯示SQL Server的IN子句非常有限,無法處理值列表。但是NOT IN子句可以很容易地不可替代的存在:

select c.description as car, dt.description as doctype 
from table_cars c 
cross join table_documenttypes dt 
where not exists 
(
    select * 
    from table_cardocuments cd 
    where cd.id_car = c.id_car 
    and cd.id_documenttype = dt.id_documenttype 
); 

更新:由於你是隻在特定id_documenttype(您不得不添加and dt.id_documenttype in (1, 2, 3, 4)到查詢)感興趣,可以生成記錄它們在飛行中而不必讀取table_documenttypes。

爲了做到這一點取代

cross join table_documenttypes dt 

cross join (values (1), (2), (3), (4)) as dt(id_documentType) 
+0

不適用於MS SQL。這樣做是這樣的: 選擇c.description如汽車,dt.description從table_carsç 交叉連接的doctype table_documenttypes dt的 其中來自table_cardocuments CD 其中cd dt.id沒有在( ( 選擇cd.id_documentType .idcar = c.id AND cd.id_doctype = dt.id ) AND dt.id IN(1,2,3,4) –

+0

「不工作」是什麼意思?出現錯誤?記錄太多?太少了?至於語法:在IN之後有一個括號太多。你寫了'NO IN'而不是'NOT IN'。 –

+0

而你的IN子句被混淆了。 IN子句應該是不相關的,但是您可以參考子查詢中的dt值。你爲什麼改變它? SQL Server不能處理元組嗎?也許。然後讓這個不存在。我會馬上編輯我的答案。 –

1

您可以使用下面的查詢得到的結果:

SELECT 
    c.description, 
    dt.description 
FROM 
    Table_Cars c 
    JOIN Table_CarDocuments cd ON c.id_car = cd.id_car 
    JOIN Table_DocumentTypes dt ON cd.id_documentType = dt.id_documentType 
WHERE 
    dt.id_documentType NOT IN (1, 2, 3, 4) --replace with your document type id 
0

這可能是一個複雜的查詢。這個想法是生成汽車和你想要的四個文件的所有組合(使用cross join)。然後使用left join,以確定是否該文件確實存在:

select c.id_car, dd.doctype 
from cars c cross join 
    (select 'doc1' as doctype union all 
     select 'doc2' union all 
     select 'doc3' union all 
     select 'doc4' 
    ) dd left join 
    CarDocuments cd 
    on c.id_car = cd.id_car left join 
    Documents d 
    on cd.id_document_type = d.id_document_type and d.doctype = dd.doctype 
where dd.id_document_type is null; 

最後,where條款認定,不存在數據車上/ DOCTYPE對。

+0

當汽車已經有一份文件(它沒有另外3份)時,它不會顯示在結果 –

+0

@DiogoAlmeida中。 。 。這很奇怪。這應該是工作。 –

0

由於@Thorsten KETTNER幫助

select c.description as car, dt.description as doctype 
from table_cars c 
cross join table_documenttypes dt 
where dt.id no in (
(
    select cd.id_documentType 
    from table_cardocuments cd 
    where cd.idcar = c.id AND cd.id_doctype = dt.id 
) 
AND dt.id IN (1, 2, 3, 4) 
相關問題