簡體   English   中英

如何管理連接表上的插入

[英]How to manage the insert on a junction table

我有兩張桌子:配料和食譜

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


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

然后我有這兩個表的連接表。

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

我不清楚應該如何在聯結表中插入數據。 我的意思是,我是否必須使用簡單的 INSERT 手動插入recipe_idingredient_id recipe_id 或者我是否必須以某種方式使用與其他兩個表的關系?

將完整關系插入所有三個表通常需要三個單獨的插入語句。 您可以通過在單個邏輯事務中執行所有插入來解決這個問題。 例如:

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 recipe_id列是串行/自動增量,那么您將在插入語句中省略它們。 如果您需要在插入后為這些表找到自動生成的 ID 值,您可以使用pg_get_serial_sequence()函數, 請參見此處

表配方和成分是獨立的表,數據可以通過簡單的查詢插入:

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

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

可以通過兩個表的選擇數據填充連接表,例如:

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');

嘗試 PostgreSQL 小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM