将数据插入具有主键的 table(多列)中,而另一个数据具有主键以外的数据

Inserting data into a table(mutliple columns) which has primary key from another data which has data except primary key

我有一个 table,它有 3 列 ID(主键)、姓名、城市。

我需要从另一个只有名称和城市的 table 导入数据。

我可以插入 table 1(Name, City) select Name, City from table2.

但是我需要 table 1 中的 ID,需要使用序列插入。

我试过这个:

插入 table1(ID, Name,City) 值(seq.nextval,select 不同名称,来自 table2 的城市)。但是我收到一条错误消息,指出值的数量不足。

我正在 SQL Oracle 中尝试。有人可以帮我解决这个问题吗?

您正在混合 insert ... valuesinsert ... select syntax

您编辑了您的问题以包含 distinct,这意味着您有重复的 name/city 对要隐藏;但两个版本都没有收到您报告的错误。如果你没有重复,那么你可以这样做:

insert into table1(ID, Name,City)
select seq.nextval, name, city from table2;

如果确实有重复项,则不能只添加 distinct 关键字,但可以使用子查询:

insert into table1 (id, name, city)
select seq.nextval, name, city
from (
  select distinct name, city
  from table2
);

db<>fiddle

您也可以通过触发器设置 ID。如果您使用的是最新版本,则可以改用标识列 - 但您使用 Oracle 11g 标记了问题,而这些不可用。