【问题标题】:Retrieving data from a many-to-many relationship in a recipes database从食谱数据库中的多对多关系中检索数据
【发布时间】:2019-08-13 21:23:39
【问题描述】:

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

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

提前致谢,如果您需要我扩展我所询问的任何内容,请询问。

【问题讨论】:

  • 你用 C# 标签标记了这个。你的代码呢?
  • 如果在 Sql Server Management Studio 中运行查询,结果是什么?
  • 要搜索“任何”成分列表,您可以使用IN,如:WHERE ingredients.name IN ('Eggs', 'Flour', 'Sugar')
  • 而且,假设 SSMS 返回一个结果,调试器呢?如果调用 ADO 或 SQL ExecuteNonQuery 或您正在执行的任何操作都返回 List 或 Enumerable,那么调试时它在哪里失败?
  • 查询是正确的,所以,如果您没有看到任何结果,我们有两种可能。 1) 没有使用“鸡蛋”成分的食谱,我们看不到您的数据库。 2)您的代码有错误,您还没有发布您的代码。这是导致关闭问题的情况,因为它缺少minimal reproducible example

标签: sql database winforms ado.net


【解决方案1】:

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

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# 解决方案中对其进行编码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 2017-01-17
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多