recipe_ingredients
保存每条生产配方消耗的材料及数量,并通过反向索引 idx_recipe_ingredients_item 支撑物品详情页的「此物品可用于制作」高速查询与分页。
表结构
(
recipe_id INTEGER NOT NULL,
pos INTEGER NOT NULL,
item_id INTEGER NOT NULL,
result_item_id INTEGER NOT NULL,
qty INTEGER NOT NULL,
PRIMARY KEY (recipe_id, pos)
) WITHOUT ROWID;
(item_id, result_item_id, recipe_id);
字段说明
| 列名 | 类型 | 约束 | 来源 | 说明 |
|---|---|---|---|---|
recipe_id | INTEGER | 联合主键 | Recipe.# | 关联 recipes.id |
pos | INTEGER | 联合主键 | Ingredient[0..7] 顺序 | 材料在配方中的有序槽位(保留原表顺序,允许同材料占位) |
item_id | INTEGER | NOT NULL | Recipe.Item{Ingredient}[k] | 材料物品 ID,关联 items.id |
result_item_id | INTEGER | NOT NULL | Recipe.Item{Result} | 冗余成品物品 ID,配合覆盖索引 (item_id, result_item_id, recipe_id) 实现无回表统计与分页 |
qty | INTEGER | NOT NULL | Recipe.Amount{Ingredient}[k] | 消耗数量(大于 0) |
常见查询
-- 1. 查某件成品的所有配方材料明细(物品页「如何制作此物品」)
SELECT ri.recipe_id, ri.item_id, ri.qty, i.name, i.icon, i.category
FROM recipe_ingredients ri
JOIN recipes r ON r.id = ri.recipe_id
LEFT JOIN items i ON i.id = ri.item_id
WHERE r.result_item_id = 1602
ORDER BY r.pos, r.id, ri.pos;
-- 2. 按材料反查成品数量与分页(如火之碎晶 id=10,全走覆盖索引无回表)
SELECT COUNT(DISTINCT result_item_id)
FROM recipe_ingredients
WHERE item_id = 10;
SELECT p.result_item_id AS product_id, i.name, i.icon, i.category
FROM (
SELECT DISTINCT result_item_id
FROM recipe_ingredients
WHERE item_id = 10
ORDER BY result_item_id
LIMIT 48 OFFSET 0
) p
LEFT JOIN items i ON i.id = p.result_item_id
ORDER BY p.result_item_id;