2015-12-02 71 views
0

我在我的DB有兩個表,用戶禮物。用戶表獲得了id和數據,禮品表獲得了gift_id,user_id和數據。Sqlite查詢所有丟失的ID

gitst.user_id與users.id

我怎樣才能得到所有從禮品表不會出現在用戶表中的user_id關聯?它使用的是except操作

回答

1

一種方式做。

select user_id from gifts 
except 
select id from users 

Except給你兩套的區別。

比方說,設置A = {1,2,3} B = {3,4,5,6}。

AB = {1,2},因爲3存在於兩個集合和1,2-存在於A而非B中

BA = {4,5,6} 3是共同的兩組和4 ,5,6存在於B,而不是在一個

你也可以做

select user_id from gifts 
where user_id not in (select id from users) 

select user_id from gifts g 
where not exists (select 1 from users where id = g.user_id) 
+0

用戶沒有user_id他們有id,請你詳細解釋except查詢的工作原理。 –

0
select user_id from gifts not exists(select id from users)