一次插入多个表的正确方法是什么?

时间:2016-05-19 03:04:07

标签: postgresql stored-procedures triggers sql-insert

例如,我有一个名为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 |  |
+----------+----+-------+--------+--+

如果我将1行数据插入product_list,部分数据(例如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_price

时,使用触发器插入其他表格,如product_list

2 - 使用product_add之类的函数(存储过程)将新产品添加到每个表中。

哪种方法更好?或者如果有更好的建议,那么我想知道它。提前谢谢。

TLDR:我应该使用Triggers还是使用Stored Procedures,哪个更好?或者你有更好的建议?

1 个答案:

答案 0 :(得分:0)

在Postgres中,您可以使用CTE:

name

注意:您不应重复product_listproduct_price表中的conda create --name backtesting python=3.4 zipline=0.9.0 pandas=0.17.1 列。它应该只在列表中。

相关问题