如何编写自定义函数以验证关系表

时间:2019-04-20 22:28:24

标签: sql postgresql

我有两个表,第一个auction表具有price列,第二个bid表具有amount列。bid表具有外部表键称为auction_id。 在向bid表中插入新行之前,我需要编写一个函数,该函数应验证bid amount必须大于auction price

3 个答案:

答案 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