我正在嘗試制作食譜資料庫。在帶有 col“ingredients”的“recipes”表中,我想要一個成分 ID 串列,例如 [2,5,7]。我可以做這樣的事情還是我應該尋找另一種解決方案?
import sqlite3
conn = sqlite3.connect('recipes.db')
c = conn.cursor()
c.execute('''CREATE TABLE recipes(ID INT, name TEXT, ingredients INT)''')
c.execute('''CREATE TABLE ingredients(ID INT, nazwa TEXT, kcal REAL)''')
另一個想法是制作另一張桌子(配料清單),其中我將有 15 個帶有配料數量的列。
c.execute('''CREATE TABLE The_list_of_ingredients(ID INT, ingredient1 INT, ingredient2 INT, ...)''')
我可以將每種成分 1、成分 2 ... 與其各自的成分 ID 聯系起來嗎?
uj5u.com熱心網友回復:
您可能正在尋找食譜與其成分之間的多對多關系。
CREATE TABLE recipes(ID INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE ingredients(ID INTEGER PRIMARY KEY, name TEXT, kcal REAL);
CREATE TABLE recipe_ingredients(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
recipe_id INTEGER,
ingredient_id INTEGER,
quantity REAL,
FOREIGN KEY(recipe_id) REFERENCES recipes(ID),
FOREIGN KEY(ingredient_id) REFERENCES ingredients(ID)
);
這樣你的資料可能看起來像
配料
| ID | 姓名 | 千卡 |
|---|---|---|
| 1 | 蛋 | 155 |
| 2 | 奶油 | 196 |
食譜
| ID | 姓名 |
|---|---|
| 1000 | 煎蛋 |
recipe_ingredients
| 配方_id | 成分_id | 數量 |
|---|---|---|
| 1000 | 1 | 100 |
| 1000 | 2 | 50 |
(假設kcal每 100 克是千卡,quantity以克為單位,還有一個相當奶油的煎蛋卷)
uj5u.com熱心網友回復:
您可以嘗試將 id 存盤為字串
json.dumps(list_of_ingredients_ids)
但可能最好的解決方案是多對多關系
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/337753.html
