如何使用外键将数据插入表中?

时间:2020-06-18 17:19:06

标签: java sql jdbc derby

我有两个表:

用户:user_id(PK) | name
产品:product_id(PK) | product | user_id(FK)

这是一对多关系(一个用户可以拥有多个产品)。我用以下语句创建了表:

String stmt_user = "create table user (user_id int not null generated by default as identity," 
                   + "name varchar(20), " 
                   + "primary key(user_id))";

String stmt_prod = "create table product (product_id int not null generated by default as identity,"
                   + "product varchar(20), "
                   + "constraint ads_pk primary key(product_id), "
                   + "foreign key(user_id)  references user(user_id) on delete cascade)";

当我想将多个产品插入ID为2的一个特定用户时该怎么办?
像这样:“在用户(用户ID)= 2的地方插入产品值(产品)”。
这是我的桌子的样子:

|---------------------|------------------|---------------|
|      product_id     |     user_id      |    product    |
|---------------------|------------------|---------------|
|          1          |         2        |     bacon     |
|---------------------|------------------|---------------|
|          2          |         2        |     pizza     |
|---------------------|------------------|---------------|
|          3          |         2        |     beans     |
|---------------------|------------------|---------------|

1 个答案:

答案 0 :(得分:0)

啊终于从这里找到了我的答案: Insert into table with a foreign key

我必须更新我的创建产品声明:

String stmt_prod = "create table product (product_id int not null generated by default as identity,"
                   + "product varchar(20), "
                   + "constraint ads_pk"
                   + "foreign key(user_id) references user(user_id) on delete cascade)";

现在我的插入产品声明如下所示:

"insert into product (product, user_id) select product, u.user_id from user u where u.user_id = 2");