在插入新行之前,我需要檢查是否進行了具有相同時間戳和產品 ID 的預訂。
我正在努力制定這項政策,如果有人能提供幫助,那就太好了。
這是我的表的架構:
create table Bookings (
id bigint not null primary key,
created_at timestamp default now(),
start timestamp default now(),
name character,
user_id uuid,
notes text,
product_id bigint references Services (id),
status text not null,
owner_id uuid default uuid_generate_v4()
);
我嘗試過使用觸發器,但沒有成功,我創建了一個函式來檢查是否存在具有相同時間戳的行和帶有時間戳的產品 id,并且產品作為輸入和布爾作為輸出。起初我以為我可以在策略中使用它,但我收到了一些錯誤,表明該功能不存在。
create or replace function same_time_bookings(bookingtime timestamp, product int)
returns boolean
as
$$
declare
returnbool boolean;
begin
SELECT case when COUNT(*) > 0
then 0
else 1
end into returnbool from "Bookings" where
product_id = product
and extract(year from start) = extract(year from bookingtime)
and extract(month from start) = extract(month from bookingtime)
and extract(day from start) = extract(day from bookingtime)
and extract(hour from start) = extract(hour from bookingtime);
return returnbool;
end;
$$ language plpgsql;
uj5u.com熱心網友回復:
您需要為 2 列product_id和start. 這樣,您可以擁有多個具有相同 product_id 但時間戳不同的行。
create table Bookings (
id bigint not null primary key,
created_at timestamp default now(),
start timestamp default now(),
product_id bigint,
UNIQUE (product_id, start) -- Add this
);
DBfiddle中的演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/478866.html
標籤:数据库 PostgreSQL 超级基础 超级数据库
上一篇:如何在JSONField的“更新”中使用DjangoF()運算式
下一篇:與函式中的變數連接會產生錯誤
