插入包含另一个值的表

时间:2017-06-19 09:08:38

标签: sql db2

我有2个表,productclient

我想根据客户端表的行数插入我的产品表行:

INSERT INTO product (
    id,
    NAME,
    client_id
)
VALUES (
    productSequence.nextval,
    'myProd',
    SELECT client_id FROM client
);

此查询错误,导致select client_id from client返回多行!

我无法找到该怎么做

2 个答案:

答案 0 :(得分:1)

使用SELECT语句而不是VALUES,这将为client表格中的每个客户端生成1行,因此如果您在client中有3条记录,则会有在product

中插入了3条记录
insert into product(id, name, client_id) 
select productSequence.nextval, 'myProd', client_id from client

如果表id中的IDENTITYproduct列(数据库提供值),则不应在您的语句中提供它,因此它将是:

insert into product(name, client_id) 
select 'myProd', client_id from client

答案 1 :(得分:1)

我不知道productSequence.nextval来自哪里。 但基本上它是一个INSERT-SELECT语句,如下所示:

INSERT INTO product
 SELECT productSequence.nextval
       ,'myProd'
       ,client_id
  FROM client
;  

告诉我productSequence.nextval列来自哪里,我将更新我的陈述

相关问题