2017-02-20 66 views
0

我有一個需要按順序執行的SQL查詢字符串,並且每個查詢都需要一個WITH查詢。事情是這樣的:使用許多更新語句重構PostgreSQL WITH查詢

WITH diff AS (
    SELECT NOW() - created_at as time_diff FROM table_a ORDER BY created_at DESC LIMIT 1 
) 
UPDATE table_x SET created_at = created_at + (SELECT time_diff FROM diff); 

WITH diff AS (
    SELECT NOW() - created_at as time_diff FROM table_a ORDER BY created_at DESC LIMIT 1 
) 
UPDATE table_y SET created_at = created_at + (SELECT time_diff FROM diff); 

WITH diff AS (
    SELECT NOW() - created_at as time_diff FROM table_a ORDER BY created_at DESC LIMIT 1 
) 
UPDATE table_a SET created_at = created_at + (SELECT time_diff FROM diff); 

這是一個稍微人爲的例子,但我們的目的是「移動」的若干表的所有記錄的created_at時間戳。由於table_a包含在所有WITH查詢中,因此它必須是要更新的最後一個表或其他所有內容都是錯誤的。

理想我只想做這樣的事情:

WITH diff AS (
    SELECT NOW() - created_at as time_diff FROM table_a ORDER BY created_at DESC LIMIT 1 
) 
UPDATE table_x SET created_at = created_at + (SELECT time_diff FROM diff) 
UPDATE table_y SET created_at = created_at + (SELECT time_diff FROM diff) 
UPDATE table_a SET created_at = created_at + (SELECT time_diff FROM diff); 

兩個,因爲它更簡潔,因爲這樣的順序將沒有真正的問題。但這顯然不是合法的語法。

有沒有辦法在單個查詢中完成此操作?

回答

2

你需要把每一次更新(除了最後一個)在CTE:

WITH diff AS (
    SELECT NOW() - created_at as time_diff FROM table_a ORDER BY created_at DESC LIMIT 1 
), upd_x as (
    UPDATE table_x SET created_at = created_at + (SELECT time_diff FROM diff) 
), upd_y as (
    UPDATE table_y SET created_at = created_at + (SELECT time_diff FROM diff) 
) 
UPDATE table_a SET created_at = created_at + (SELECT time_diff FROM diff);