![](/img/trans.png)
[英]Is there anyway to insert data to table with 2 different foreign keys from 2 different tables?
[英]How do I insert data into a table with foreign keys?
我有两张桌子:
用户: user_id(PK) | name
user_id(PK) | name
产品: product_id(PK) | product | user_id(FK)
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 的特定用户时,我该怎么办?
像这样:“插入产品值(产品),其中用户(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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.