【发布时间】:2016-05-19 03:04:07
【问题描述】:
例如,我有一个名为 product_list 的表,其中包含产品列表:
+----+-------+-----------+-------------+--+
| id | name | weight(g) | type | |
+----+-------+-----------+-------------+--+
| 1 | Shirt | 157 | Clothes | |
+----+-------+-----------+-------------+--+
| 2 | Ring | 53 | Accessories | |
+----+-------+-----------+-------------+--+
| 3 | Pants | 202 | Clothes | |
+----+-------+-----------+-------------+--+
还有一个名为product_price的表:
+----------+----+-------+--------+--+
| price_id | id | name | price | |
+----------+----+-------+--------+--+
| 1 | 1 | Shirt | 99.00 | |
+----------+----+-------+--------+--+
| 2 | 2 | Ring | 149.00 | |
+----------+----+-------+--------+--+
| 3 | 3 | Pants | 119.00 | |
+----------+----+-------+--------+--+
如果我在 product_list 中插入 1 行数据,部分数据(例如 product_id 和 product name)也应该插入到另一个表中,例如 product_price,其中包含所有产品的价格(新产品的价格将具有 0 或 NULL 值)。例如:
product_list:
+----+--------+-----------+-------------+--+
| id | name | weight(g) | type | |
+----+--------+-----------+-------------+--+
| 1 | Shirt | 157 | Clothes | |
+----+--------+-----------+-------------+--+
| 2 | Ring | 53 | Accessories | |
+----+--------+-----------+-------------+--+
| 3 | Pants | 202 | Clothes | |
+----+--------+-----------+-------------+--+
| 4 | Shirt2 | 175 | Clothes | |
+----+--------+-----------+-------------+--+
product_price:
+----------+----+-------+--------+--+
| price_id | id | name | price | |
+----------+----+-------+--------+--+
| 1 | 1 | Shirt | 99.00 | |
+----------+----+-------+--------+--+
| 2 | 2 | Ring | 149.00 | |
+----------+----+-------+--------+--+
| 3 | 3 | Pants | 119.00 | |
+----------+----+-------+--------+--+
| 4 | 4 | Shirt2| 0.00 | |
+----------+----+-------+--------+--+
我的问题是解决这个问题的方法。有经验的人处理这个问题的正确方法是什么(以专业的方式)?
这是我想到的两种方法:
1 - 每当我将产品数据插入product_list 时,使用触发器插入到product_price 等其他表中
2 - 使用类似product_add 的函数(存储过程)将新产品添加到每个表中。
哪种方法更好?或者如果有更好的建议,那么我想知道它。提前致谢。
TLDR:我应该使用Triggers 还是使用Stored Procedures,哪个更好?或者你有更好的建议?
【问题讨论】:
标签: postgresql stored-procedures triggers sql-insert