在 PostgreSQL 中根据另一个 table 更新一个 table
Update a table based on another table in PostgreSQL
我有两个 table:
产品
| id | name | price | type_id
------------------------------------
| 1 | Product A | 500 | 1
| 2 | Product B | 600 | 3
| 3 | Product C | 800 | 15
类型
| id | price |
---------------
| 1 | |
| 3 | |
| 15 | |
现在我想将 types table 中的价格设置为 products [=40] 中的值=]对应的是type_id
因此在类型 table 1 => 500, 3 => 600, 15 => 800
中,鉴于 type_id 在产品 table 中是唯一的。
我尝试编写如下查询:
UPDATE types SET price = (
SELECT sub.price FROM (SELECT p.type_id AS id, p.price AS price
FROM products p, types t
WHERE p.type_id = t.id) AS sub
WHERE sub.id = types.id
)
但是,查询无法正常工作并且似乎过于复杂。我应该怎么做?
如果一个类型最多只能归因于一个产品,那么:
UPDATE types set price = products.price
from products where products.type_id= types.id
我有两个 table:
产品
| id | name | price | type_id
------------------------------------
| 1 | Product A | 500 | 1
| 2 | Product B | 600 | 3
| 3 | Product C | 800 | 15
类型
| id | price |
---------------
| 1 | |
| 3 | |
| 15 | |
现在我想将 types table 中的价格设置为 products [=40] 中的值=]对应的是type_id
因此在类型 table 1 => 500, 3 => 600, 15 => 800
中,鉴于 type_id 在产品 table 中是唯一的。
我尝试编写如下查询:
UPDATE types SET price = (
SELECT sub.price FROM (SELECT p.type_id AS id, p.price AS price
FROM products p, types t
WHERE p.type_id = t.id) AS sub
WHERE sub.id = types.id
)
但是,查询无法正常工作并且似乎过于复杂。我应该怎么做?
如果一个类型最多只能归因于一个产品,那么:
UPDATE types set price = products.price
from products where products.type_id= types.id