2017-02-20 11 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に(最後の1を除く)各更新を配置する必要があります。

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); 
関連する問題