用于在连接期间更新不同表中的多个列的Postgresql查询

时间:2016-12-12 10:40:12

标签: mysql postgresql

我们正致力于将数据从MySQL迁移到PostgreSQL。

示例表结构:

                     Table "public.model"
       Column       |            Type             | Modifiers 
--------------------+-----------------------------+-----------
 model_id           | integer                     | not null
 last_purchase_time | timestamp without time zone | 
Indexes:
    "model_pkey" PRIMARY KEY, btree (model_id)
Referenced by:
    TABLE "items" CONSTRAINT "items_model_id_fkey" FOREIGN KEY (model_id) REFERENCES model(model_id)

                  Table "public.items"
    Column     |            Type             | Modifiers 
---------------+-----------------------------+-----------
 item_id       | integer                     | not null
 purchase_time | timestamp without time zone | 
 model_id      | integer                     | 
Indexes:
    "items_pkey" PRIMARY KEY, btree (item_id)
Foreign-key constraints:
    "items_model_id_fkey" FOREIGN KEY (model_id) REFERENCES model(model_id)
Referenced by:
    TABLE "invoice" CONSTRAINT "invoice_item_id_fkey" FOREIGN KEY (item_id) REFERENCES items(item_id)

                 Table "public.invoice"
    Column    |            Type             | Modifiers 
--------------+-----------------------------+-----------
 inovoice_id  | integer                     | not null
 invoice_time | timestamp without time zone | 
 item_id      | integer                     | 
Indexes:
    "invoice_pkey" PRIMARY KEY, btree (inovoice_id)
Foreign-key constraints:
    "invoice_item_id_fkey" FOREIGN KEY (item_id) REFERENCES items(item_id)

如果我们使用join更新单个表的列,那么我们可以在postgresql中使用以下查询。

update model
   set last_purchase_time = now()
from items
     join invoice
        on items.item_id = invoice.item_id
where model.model_id = items.model_id
  and invoice.item_id = 2002;

以下是更新所有表中多列的更新查询,在MySQL中可以正常工作。

update model
       join items
          on model.model_id = items.model_id
       join invoice
          on items.item_id = invoice.item_id
set model.last_purchase_time = now(),
    items.purchase_time = now(),
    invoice.invoice_time = now()
where invoice.item_id = 2002;

有人可以使用join来建议使用等效的PostgreSQL查询来更新不同表中的多个列吗?

1 个答案:

答案 0 :(得分:1)

你可以在PostgreSQL中这样做:

WITH upd1 AS
        (UPDATE invoice
         SET invoice_time = current_timestamp
         FROM items
            JOIN model
               ON model.model_id = items.model_id
         WHERE items.item_id = invoice.item_id
            AND invoice.item_id = 2002
         RETURNING model.model_id, items.item_id),
     upd2 AS
        (UPDATE items
         SET purchase_time = current_timestamp
         FROM upd1
         WHERE upd1.item_id = items.item_id)
UPDATE model
SET last_purchase_time = current_timestamp
FROM upd1
WHERE upd1.model_id = model.model_id;

唯一的缺点是itemsmodel的更新频率会超出必要的范围。