2015-06-09 57 views
0

我有一張contributions的表格和另一張表格profiles。我想select all profiles沒有相關的貢獻。選擇一列中不在另一個表格列中的所有值

我可以加入contributions.profiles_id = profiles.id上的兩個表格。

真的很感謝任何幫助!

+2

這通常用'未達到EXISTS'和一個相關的子查詢,或一個'LEFT JOIN',然後通過比較任何右表列和空來檢測缺失的連接。 – StuartLC

回答

1
Try this. 

select p.* from profiles p 
left join contributions c on p.profile_id=c.profie_id 
where c.profile_id is NULL ; 
+0

假設c.profile_id不是一個可爲空的列,我會去那。如果它是可空的,我會建議使用'not exists'來代替。 –

0

*您所需要的查詢是:

SELECT 
    colA, 
    colB, 
    .... 
FROM contributions tb1 
WHERE 
    NOT EXISTS (SELECT * from profiles tb2 where tb1.profiles_id = tb2.id) 
GROUP BY 
    colA, 
    colB, 
    .... 
+0

你也可以使用不IN.'INSERT INTO TABLEA ( COL1,COL2 ) 選擇 可樂, COLB, .... FROM 貢獻TB1 WHERE tb1.profiles_id NOT IN(SELECT TB2 .id from profiles tb2 group by tb2.id) GROUP BY colA, colB, .... ;' –

+0

你沒有回答這個問題。 INSERT不是答案。 – jarlh

+0

@ZoharPeled,取決於使用的dbms。 (沒有人在這裏指定......) – jarlh

2

使用NOT EXISTS地發現,有沒有相關的捐款概況:

select * from profiles p 
where NOT EXISTS (select 1 from contributions c 
        where c.profiles_id = p.id); 
相關問題