2016-07-30 78 views
1

我有一個多對多的關係,代表container s擁有item s。返回子句是否總是首先執行?

我在表中有一個主鍵row_id。

我插入四行:(container_id, item_id) values (1778712425160346751, 4)。除了上述獨特的row_id外,這些行將是相同的。

隨後,我執行以下查詢:

delete from contains 
    where item_id = 4 and 
    container_id = '1778712425160346751' and 
    row_id = 
     (
      select max(row_id) from contains 
      where container_id = '1778712425160346751' and 
      item_id = 4 
     ) 
    returning 
     (
      select count(*) from contains 
      where container_id = '1778712425160346751' and 
      item_id = 4 
     ); 

現在,我希望拿到3從該查詢返回的,但我得到了一個4獲得一個4所期望的行爲,但它不是什麼預期。

我的問題是:我可以一直期望returning子句在刪除之前執行,還是這是某些版本或特定軟件的特質?

回答

2

允許使用returning部分中的查詢,但沒有記錄。對於the documentation

output_expression

的表達式被計算,並且每個行被刪除之後,由DELETE命令返回。該表達式可以使用table_name命名的表的任何列名或USING中列出的表的任何列名。寫*返回所有列。

由於語句尚未完成,查詢看到表在刪除之前的狀態似乎是合乎邏輯的。

create temp table test as 
select id from generate_series(1, 4) id; 

delete from test 
returning id, (select count(*) from test); 

id | count 
----+------- 
    1 |  4 
    2 |  4 
    3 |  4 
    4 |  4 
(4 rows) 

了同樣的擔憂update

create temp table test as 
select id from generate_series(1, 4) id; 

update test 
set id = id+ 1 
returning id, (select sum(id) from test); 

id | sum 
----+----- 
    2 | 10 
    3 | 10 
    4 | 10 
    5 | 10 
(4 rows)  
+0

我想指出的是,如果我做一個更新似乎返回的值是值** **後的更新。插入關於由沙子製成的城堡的評論... – tenCupMaximum

+1

刪除或更新的列的值始終是最新的,我們在討論'returns'子句中的**子查詢**。 – klin

+0

啊,我看到,如果我'返回select從表'updatedColumn它會得到舊值,如果我'返回updatedColumn'它會得到更新的值。這是一個明智的結果。 – tenCupMaximum