[英]Can we insert in one table and trigger to update the inserted row's one column by looking at other table's value for the id being inserted?
How to write a trigger which upon insert
in table3
looks at table1
if the code
and id
has a price
there first and updates the price
of table3
accordingly.如何编写一个触发器,在
insert
table3
查看table1
如果code
和id
首先在那里有price
,并相应地更新table3
的price
。 But if the id
+ code
cannot be found then it looks in table2
for the id
and uses that price to calculate the total price
and updates the price
in table3
for that insert.但是,如果找不到
id
+ code
那么它会在table2
查找id
并使用该价格来计算price
并更新table3
中该插入的price
。
table1表格1
| id | code | price |
|----|------|-------|
| 1 | fire | 3 |
| 2 | ice | 4 |
| 3 | air | 5 |
table2表2
| id | price |
|----|-------|
| 1 | 8 |
| 2 | 9 |
table3表3
| id | code | qty | price |
|----|------|-----|-------|
| 1 | fire | 2 | | -- price = 2 * 3 = 6
| 2 | none | 3 | | -- price = 3 * 9 = 27
In your trigger function you should use if exists
to check it.在您的触发器函数中,您应该使用
if exists
来检查它。 You can write your trigger function like below:您可以编写如下触发器函数:
CREATE FUNCTION update_price()
RETURNS trigger AS $$
BEGIN
if exists (select price from table1 where code=new.code and id=new.id) then
new.price= new.qty * (select price from table1 where code=new.code and id=new.id);
else
new.price= new.qty * (select price from table2 where id=new.id);
end if;
return new;
END;
$$ LANGUAGE plpgsql;
Then you can write your trigger on table3
as below:然后你可以在
table3
上写你的触发器,如下所示:
create trigger update_price
before insert
on table3
for each row
execute procedure update_price();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.