我有一個 PostgreSQL 表,第一個包含有關訂單的基本資訊,第二個表包含參考的訂單 ID 內的產品。我的問題是如何以正確的方式將資料發布到這兩個表中?還是我應該將我的計劃更改為更完善的計劃?
表如下所示:

uj5u.com熱心網友回復:
這里沒有表設計問題,這是正常的一對多關系。但只是為了確保這里的資料完整性,您應該在資料庫中使用事務。要在將記錄插入多個表時正確保護資料完整性,您有兩種選擇:
- 使用事務
- 撰寫單個查詢(一條陳述句)以同時插入兩個表
在 PostgreSQL 中,任何函式都是通過事務執行的,所以一個函式 = 一個事務。例如:
CREATE OR REPLACE FUNCTION inser_all_order_data(
)
RETURNS void
LANGUAGE plpgsql
AS $function$
declare
orderid integer;
begin -- begin transaction
insert into orders (created_at, type, status) values (now(), 'mytype', 'mystatus')
returning id into orderid;
insert into ordercontent (order_id, code, name, content) values (orderid, '001', 'myname', 'some text');
end; -- end transaction
$function$
;
在這里,兩個插入陳述句都在同一個事務中。
撰寫單個查詢的示例:
with tb as (
insert into orders (created_at, type, status) values ??(now(), 'mytype', 'mystatus')
returning id
)
insert into ordercontent (order_id, code, name, content)
select id, '001', 'myname', 'some text' from tb;
當您撰寫單個查詢時,您需要使用事務,因為一個陳述句 = 一個事務。
如果您不需要同時向兩個表中插入記錄,那么您可以照常使用插入陳述句。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/528349.html
上一篇:在兩個PHP頁面之間傳遞資料
