Postgresql

從刪除表中選擇同一列時,PSQL cte delete 似乎有歧義

  • December 3, 2020

這兩個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只有一個 column seller_id

您的第一個查詢刪除了所有行,因為idinselect id from d0不能引用來自 的列d0,因此它被視為外部查詢的列,整個事情實際上變成了

WITH d0 AS (...)
DELETE FROM seller
WHERE seller.id IN (SELECT seller.id FROM d0)

d0並且只要不為空,該條件就會為真。

引用自:https://dba.stackexchange.com/questions/280790