如何使用外键将数据插入 table?
How do I insert data into a table with foreign keys?
我有两个 table:
用户:user_id(PK) | name
产品:product_id(PK) | product | user_id(FK)
这是一对多的关系(一个用户可以有多个产品)。我使用以下语句创建了 tables:
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 的特定用户时,我该怎么办?
像这样:"insert into product values(product) where user(user_id) = 2".
我的 table 应该是这样的:
|---------------------|------------------|---------------|
| 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");
我有两个 table:
用户:user_id(PK) | name
产品:product_id(PK) | product | user_id(FK)
这是一对多的关系(一个用户可以有多个产品)。我使用以下语句创建了 tables:
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 的特定用户时,我该怎么办?
像这样:"insert into product values(product) where user(user_id) = 2".
我的 table 应该是这样的:
|---------------------|------------------|---------------|
| 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");