我有两个表,第一个auction
表具有price
列,第二个bid
表具有amount
列。bid
表具有外部表键称为auction_id
。
在向bid
表中插入新行之前,我需要编写一个函数,该函数应验证bid amount
必须大于auction price
。
答案 0 :(得分:0)
您也许也可以在出价表中写一个价格,它的大小比较大,但是不需要触发器,输入检查将更快,因为它不需要额外的查找。
CREATE TABLE auction (
auction_id serial PRIMARY KEY,
price money NOT NULL
);
-- requires extra idx as well
CREATE UNIQUE INDEX ON auction (auction_id, price);
CREATE TABLE bid (
bid_id serial PRIMARY KEY,
auction_id int NOT NULL,
price money NOT NULL,
bid money NOT NULL CHECK (bid > price),
FOREIGN KEY (auction_id, price) REFERENCES auction (auction_id, price) ON UPDATE CASCADE ON DELETE CASCADE
);
答案 1 :(得分:0)
我找到了解决方法
CREATE OR REPLACE FUNCTION bid_func() RETURNS trigger AS $$
DECLARE
p NUMERIC;
query TEXT;
BEGIN
query := format('SELECT price FROM %I WHERE id = %L', 'auction', NEW.auction_id);
EXECUTE query INTO p;
IF NEW.amount < p THEN
RAISE EXCEPTION 'bid amount must be greater than auction price!!';
END IF;
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
答案 2 :(得分:-1)
尝试一下。
使用选择语句插入
insert into bid
select <auction_id>, amount
from auction
where auction_id = <auction_Id> and price < amount