简体   繁体   English

我们可以插入一张表并通过查看其他表的值来更新插入行的一列吗?

[英]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如果codeid首先在那里有price ,并相应地更新table3price 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();

DEMO 演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 INSERT可以在触发器“插入”表中产生多行吗? - Can an INSERT result in more than one row in a trigger “inserted” table? 使用触发器更改插入行的列的值 - Change value of inserted row's column with trigger 触发插入表中的数据保留以及一列上的更新和插入组合 - Triggers data retention in inserted table and combination of update and insert on one column SQL Server:如果在一个表中插入一行,我如何编写触发器以在不同的表中插入同一行? - SQL Server: If a row is inserted in one table, how do I write a trigger to insert that same row in a different table? 当我插入到一个表中时,如何创建触发器以便将插入的数值汇总到另一个表的列中? - When I insert into a table, how do I create a trigger such that the inserted numeric value is summed up in another table's column? SQL插入,更新触发器-您可以更新插入的表吗? - SQL Insert, Update Trigger - Can you update the inserted table? 在mysql中插入一个表时如何更新到另一个表 - How to update to other table when inserted into one table in mysql insert into select,使用inserted Id更新selected table中的column - Insert into select, use inserted Id to update column in selected table 当一个表中的列值更改时,应在oracle DB的另一表中插入一条记录 - When value of a column changes in one table , a record should be inserted in other table in oracle DB 使用插入的标识ID更新表行 - Update table row with inserted identity ID
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM