gpt4 book ai didi

java - 如何将数据插入带有外键的表中?

转载 作者:行者123 更新时间:2023-12-01 16:13:48 25 4
gpt4 key购买 nike

我有两个表:

用户:user_id(PK) |名称
产品:product_id(PK) |产品 | 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 的某个特定用户插入多个产品时,我该怎么办?
像这样:“插入产品值(产品),其中用户(user_id)= 2”。
我的表格应该是这样的:

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

最佳答案

啊终于从这里找到了我的答案: 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");

关于java - 如何将数据插入带有外键的表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62455737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com