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

Retrieving data from a many-to-many relationship in a recipes database

我正在尝试创建一个食谱数据库,用户可以在其中输入成分,它会输出一个潜在食谱列表。我创建了三个表:

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 语句来检索所有包含 'Eggs' 的食谱,使用:

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 语句。

在此先感谢,如果您需要我扩展我所问的任何问题,请询问。

这是应该有效的查询。建议使用别名

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 运行 确定 return 结果,然后再将其编码为 C# 解决方案。