如何管理连接点上的插入 table

How to manage the insert on a junction table

我有两个 table:配料和配方

recipe table
-----------------------
|recipe_id   |name  |
-----------------------
|1           |Pasta |
|2           |Pizza |
|3           |Fish  |


ingredient table
-------------------------------
|ingredient_id   |name        |
-------------------------------
|1               |Spaghetti   |
|2               |Salmon      |
|3               |Tomato sauce|

然后我有一个连接 table 这两个 table。

---------------------------
|id|recipe_id|ingredient_id|
---------------------------
|1 |1        |1            |
|2 |2        |3            |
|3 |3        |2            |

我不清楚应该如何在联结点 table 中插入数据。我的意思是,我是否必须使用简单的 INSERT 手动插入 recipe_idingredient_id?或者我是否必须以某种方式使用与其他两个 table 的关系?

将完整关系插入所有三个表通常需要三个单独的插入语句。您可以通过在单个逻辑事务中执行所有插入来处理此问题。例如:

BEGIN;  -- start transaction

INSERT INTO recipe (recipe_id, name) VALUES (1, 'Pasta');
INSERT INTO ingredient (ingredient_id, name) VALUES (1, 'Spagehetti');
INSERT INTO junction_table (recipe_id, ingredient_id) (1, 1);

COMMIT; -- end transaction

实际上,如果 recipe_idingredient_id 列是 serial/auto 递增的,那么您可以从插入语句中省略它们。如果您需要在插入后为这些表查找自动生成的 ID 值,您可以使用 pg_get_serial_sequence() 函数,see here.

table的食谱和配料是独立的table,可以通过简单的查询插入数据:

insert into recipe (name) values ('Pasta'), ('Pizza '), ('Fish');

insert into ingredient (name) values ('Spaghetti'), ('Salmon '), ('Tomato sauce'); 

结点 table 可以由两个 table 的 select 数据填充,例如:

insert into recipe_ingredient (recipe_id, ingredient_id)
select recipe_id, ingredient_id
from recipe, ingredient
where recipe.name = 'Pasta' and ingredient.name in ('Spaghetti', 'Tomato sauce');

Try PostgreSQL fiddle