Postgresql
從刪除表中選擇同一列時,PSQL cte delete 似乎有歧義
這兩個sql都可以執行,第一個刪除所有,第二個是邏輯對。
第一個
with d0 as ( delete from seller_create_request where seller_id in ( select id from seller where email in ('xx@xx.com') ) returning seller_create_request.seller_id ) delete from seller where id in (select id from d0) returning seller.id;
第二個
with d0 as ( delete from seller_create_request where seller_id in ( select id from seller where email in ('xx@xx.com') ) returning seller_create_request.seller_id ) delete from seller where id in (select d0.seller_id from d0) returning seller.id ;
第一個
select id from d0
似乎等於select id from seller
。我的初衷是select seller_id from d0
拼寫錯誤。它不會導致
column id does not exist
因為它從 d0 開始。所以我很奇怪為什麼 psql 有這種行為,我從簡單的理解中遺漏了什麼?
您的第二個查詢將失敗,因為
d0
只有一個 columnseller_id
。您的第一個查詢刪除了所有行,因為
id
inselect id from d0
不能引用來自 的列d0
,因此它被視為外部查詢的列,整個事情實際上變成了WITH d0 AS (...) DELETE FROM seller WHERE seller.id IN (SELECT seller.id FROM d0)
d0
並且只要不為空,該條件就會為真。