PostgreSQL:使用SERIAL列和带有子查询的初始化表

时间:2019-04-30 08:42:48

标签: postgresql

http://www.sqlfiddle.com/#!17/5c665/1

我已经制作了productspub_products表,并试图将数据从pub_products复制到products

产品:

+--------------+-----------------------+
| Column       | Type                  |
|--------------+-----------------------+
| product_id   | character(3)          |
| product_name | character varying(20) |
| inventory    | integer               |
| price        | integer               |
| manufacturer | character varying(20) |
+--------------+-----------------------+

pub_products:

+---------------+-----------------------+
| Column        | Type                  |                                                            
|---------------+-----------------------+
| hproduct_id   | integer               | <-- serial
| hproduct_name | character varying(20) |
| hinventory    | integer               |
| hprice        | integer               |
+---------------+-----------------------+

我想从product_name表中选择inventorypriceproducts列,并将它们插入到pub_products表中。

INSERT INTO pub_products (hproduct_id, hproduct_name, hinventory, hprice)
SELECT product_name, inventory, price
FROM products
WHERE manufacturer = 'Factory3';

但是DBMS说“ INSERT具有比表达式更多的目标列”。为什么会这样呢?据我所知,PostgreSQL的SERIAL列(hproduct_id)是自动增量列,因此我没有给出任何初始值。如何为SERIAL列提供默认值?

1 个答案:

答案 0 :(得分:3)

从目标表的列列表中删除该列,然后Postgres将应用默认值:

INSERT INTO pub_products (hproduct_name, hinventory, hprice)
SELECT product_name, inventory, price
FROM products
WHERE manufacturer = 'Factory3';