2016-01-05 65 views
0

我想做類似以下的事情;最簡單的方法是什麼?從列表中選擇不在表格中的值?

SELECT id FROM (1,2,3) WHERE ID NOT IN (SELECT id FROM table) 

這個想法不是通過首先將表ID加載到腳本中來增加我的python腳本的內存使用量。 我能想到的唯一方法是使用WITH查詢來構建一個臨時表,該查詢有點冗長。

回答

0
select id from (values (1),(2),(3)) as s(id) 
except 
select id from table 

要與Psycopg做到這一點:

id_list = ['1','2','3'] 
q = """ 
    select array_agg(id) 
    from (
     select id from (values {}) s(id) 
     except 
     select id from table 
    ) t; 
""".format(','.join(['%s'] * len(id_list))) 

print cur.mogrify(q, [(id,) for id in id_list]) 
# cur.execute(q, [(id,) for id in id_list]) 

輸出:

select array_agg(id) 
from (
    select id from (values ('1'),('2'),('3')) s(id) 
    except 
    select id from table 
) t; 
+0

出色的替代方案,謝謝 – jayshilling

0

提供的答案就像一個魅力,但我無法得到它具有內置的字符串psycopg2工作因爲每個值都需要在提供的答案中使用括號,所以除了手動構建查詢字符串之外,還不確定是否有解決方法。

q = "select id from (values %s as s(id) 
except 
select id from table" 
cur.execute(q, (id_list,)) 

以下是工作,因爲psycopg2有Python列表> Postgres的陣列轉換

select array_agg(ids) 
from (
    select unnest(ARRAY['1', '2']) 
    except 
    select unnest(array_agg(sku::text)) from table 
) t (ids); 
+0

與Psycopg代碼更新。 –