【发布时间】:2016-03-31 23:27:59
【问题描述】:
我有一个简单的食谱数据库,我正在尝试编写一个查询,以获取食谱以及所有相关的成分和步骤。配方本身与成分具有多对多关系(以促进成分条目的重复使用)和与步骤的一对多关系(可能一个配方与另一个配方没有相同的步骤,因此不需要在这里重复使用)。
数据库是这样设置的:
CREATE TABLE Recipe (
_id INTEGER PRIMARY KEY,
recipe_name TEXT UNIQUE NOT NULL
);
CREATE TABLE Ingredient (
_id INTEGER PRIMARY KEY,
ingredient TEXT UNIQUE NOT NULL
);
CREATE TABLE RecipeIngredient (
_id INTEGER PRIMARY KEY,
recipe_id INTEGER,
ingredient_id INTEGER,
amount REAL,
FOREIGN KEY (recipe_id) REFERENCES Recipe(_id),
FOREIGN KEY (ingredient_id) REFERENCES Ingredient(_id)
);
CREATE TABLE Step (
_id INTEGER PRIMARY KEY,
instruction TEXT NOT NULL,
number INTEGER NOT NULL,
recipe_id INTEGER,
FOREIGN KEY (recipe_id) REFERENCES Recipe(_id)
);
我可以通过 _id 在所有表上使用 INNER JOINS 提取给定食谱的所有信息(这会创建大量重复数据),但我遇到的问题是如何将其分组/订购使数据有用而不需要对结果进行额外解析以获得有意义的对象?在 2 个查询中这样做会更好吗(一个查询成分,一个查询步骤)?
更新
添加一些从选择一个配方 ID 返回的示例数据,在表之间进行 INNER JOIN(按成分/步骤编号排序):
|| recipe || || ingredient|| ||step|| ||step number||
"Recipe One" "Ingredient 1" "Step 1" "1"
"Recipe One" "Ingredient 1" "Step 2" "2"
"Recipe One" "Ingredient 1" "Step 3" "3"
"Recipe One" "Ingredient 2" "Step 1" "1"
"Recipe One" "Ingredient 2" "Step 2" "2"
"Recipe One" "Ingredient 2" "Step 3" "3"
"Recipe One" "Ingredient 3" "Step 1" "1"
"Recipe One" "Ingredient 3" "Step 2" "2"
"Recipe One" "Ingredient 3" "Step 3" "3"
【问题讨论】:
-
向我们展示一些数据以及您想要的结果。同时向我们展示您的
INNER JOIN和duplicated data,我们也可以解决这个问题。您可以在 sqlFiddle.com 上创建一个工作示例。使用Text to DDL加载您的数据库架构 -
@JuanCarlosOropeza 添加了更多信息,但从 Thorsten 的回答来看,我认为最好将其分成两个查询。