2017-06-19 46 views
0

插入表与值I有2个表,productclient从另一个

我想根据我的客户表中的行的数量在我的产品表中的行插入:

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

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

我无法找到如何做到这一点

+1

你在哪里得到productSequence.nextval而来? –

+0

当我使用db2数据库时,每个表都有一个序列来生成id。 – junior

回答

1

使用SELECT语句而不是VALUES,这将产生1排在client表中的每个客户端,这样,如果你有3条记录client你将有3插入在product

insert into product(id, name, client_id) 
select productSequence.nextval, 'myProd', client_id from client 

如果idIDENTITY列记录(数据库提供的值)在表product不应该在所有的在你的声明中提出这样的话这将是:

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

插入产品(id,name,client_id) select productSequence.nextval,'myProd',客户端client_id为我工作:) 非常感谢 – junior

+0

@junior - 很高兴为您提供帮助。请考虑在15分钟宽限期过期后使用答案左侧的复选标记标记答案。 – Igor

1

我不知道productSequence.nextval来自哪里。 但基本上它是一个INSERT-SELECT语句象下面这样:

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

告诉我在哪里列productSequence.nextval是从哪里来的,我会更新我的发言

+0

我使用db2数据库,为每个表我有一个序列来生成id。 productSequence是我用于产品表的序列。 – junior