PostgreSQL- 将查询结果插入现有 table,自动递增 id
PostgreSQL- insert result of query into exisiting table, auto-increment id
我使用以下 SQL 语句创建了一个空的 table。我的理解(基于本教程:https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-serial/)是 SERIAL PRIMARY KEY
将自动为每个新行提供一个自动递增的 id:
CREATE TABLE "shema".my_table
(
id SERIAL PRIMARY KEY,
transaction text NOT NULL,
service_privider text NOT NULL,
customer_id text NOT NULL,
value numeric NOT NULL
)
WITH (
OIDS = FALSE
);
ALTER TABLE "shema".my_table
OWNER to admin;
现在我正在查询另一个 table 并想将该查询的结果保存到 my_table
。查询结果输出如下模式:
transaction
service_provider
customer_id
value
表示 my_table
减去 id
的模式。当我尝试执行时:
INSERT into my table
Select {here is the query}
然后我收到一个错误 column "id" is of type integer but expression is of type text
。我将其解释为 sql 查询正在寻找 id
列但找不到它。如何在不明确说明 id
数字的情况下将数据插入 my_table
,但为每一行自动生成此 id
?
始终提及要插入的列:
INSERT INTO schemaname.my_table("transaction", service_privider, customer_id, value)
SELECT ?, ?, ?, ?;
如果不这样做,您的代码现在或将来会出错。
对了,事务是保留字,尽量使用更好的列名。
我使用以下 SQL 语句创建了一个空的 table。我的理解(基于本教程:https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-serial/)是 SERIAL PRIMARY KEY
将自动为每个新行提供一个自动递增的 id:
CREATE TABLE "shema".my_table
(
id SERIAL PRIMARY KEY,
transaction text NOT NULL,
service_privider text NOT NULL,
customer_id text NOT NULL,
value numeric NOT NULL
)
WITH (
OIDS = FALSE
);
ALTER TABLE "shema".my_table
OWNER to admin;
现在我正在查询另一个 table 并想将该查询的结果保存到 my_table
。查询结果输出如下模式:
transaction
service_provider
customer_id
value
表示 my_table
减去 id
的模式。当我尝试执行时:
INSERT into my table
Select {here is the query}
然后我收到一个错误 column "id" is of type integer but expression is of type text
。我将其解释为 sql 查询正在寻找 id
列但找不到它。如何在不明确说明 id
数字的情况下将数据插入 my_table
,但为每一行自动生成此 id
?
始终提及要插入的列:
INSERT INTO schemaname.my_table("transaction", service_privider, customer_id, value)
SELECT ?, ?, ?, ?;
如果不这样做,您的代码现在或将来会出错。
对了,事务是保留字,尽量使用更好的列名。