从食谱数据库中的多对多关系中检索数据

时间:2019-03-22 20:20:18

标签: sql database winforms ado.net

我正在尝试创建一个食谱数据库,用户可以在其中输入配料,并且它将输出潜在食谱的列表。我创建了三个表:

CREATE TABLE [dbo].[Ingredients] (
[Ingredient_ID] INT          IDENTITY (1, 1) NOT NULL,
[Name]          VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Ingredient_ID] ASC)
);

CREATE TABLE [dbo].[recipes] (
[Recipe_ID]        INT          IDENTITY (1, 1) NOT NULL,
[Name]             VARCHAR (50) NOT NULL,
[Instructions]     TEXT         NULL,
[Preperation_Time] FLOAT (53)   NULL,
[Author]           VARCHAR (50) NULL,
CONSTRAINT [PK.recipes] PRIMARY KEY CLUSTERED ([Recipe_ID] ASC)
);

 CREATE TABLE [dbo].[RecipeIngredients] (
[Recipe_ID]     INT NOT NULL,
[Ingredient_ID] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Recipe_ID] ASC, [Ingredient_ID] ASC),
CONSTRAINT [FK_RecipeIngredients_To_Ingredients] FOREIGN KEY ([Ingredient_ID]) REFERENCES [dbo].[Ingredients] ([Ingredient_ID]),
CONSTRAINT [FK_RecipeIngredients_To_Recipes] FOREIGN KEY ([Recipe_ID]) REFERENCES [dbo].[recipes] ([Recipe_ID])
);

我已经填充了所有表格,现在尝试根据用户输入的内容检索配方。

我创建了一个测试SQL语句,以使用以下方式检索包含“鸡蛋”的所有配方:

string sqlString = "SELECT recipes.Name, Instructions, recipes.Preperation_Time, Author FROM RecipeIngredients" +
                           " INNER JOIN recipes ON recipes.Recipe_ID = RecipeIngredients.Recipe_ID" +
                           " INNER JOIN Ingredients ON Ingredients.Ingredient_ID = RecipeIngredients.Ingredient_ID" +
                           " WHERE ingredients.Name = 'Eggs'";

数据没有显示在我的dataGridView中,但是我不确定是否是因为该语句错误或其他因素。

该陈述正确吗?我不熟悉INNER JOIN命令。

我也不确定如何设计一个可以采用不同成分名称的Sql语句,而不必为每种可能性创建Sql语句。

预先感谢您,如果您需要我提供我所要求的任何内容,请询问。

1 个答案:

答案 0 :(得分:0)

这是应该起作用的查询。建议使用别名

SELECT r.Name, r.Instructions, r.Preperation_Time, r.Author 
FROM Ingredients i 
join RecipeIngredients ri on i.Ingredient_ID = ri.Ingredient_ID
join recipes r on ri.Recipe_ID = r.Recipe_ID
where i.Name = 'Eggs'

您可能希望通过SQL Server Management Studio运行它,以确保在使用C#解决方案进行编码之前返回结果。

相关问题