sql—从mysql中包含特定数据的表中获取2个值

cclgggtu  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(281)

我需要查询字符串能够找到2个值,由用户插入他们的名字。
每个值中应有一个 Ingredient1 而且在 Ingredient2 (不是两者都有)。如何在sql查询中实现这一点?
这是我迄今为止尝试过的

public static List<IngredientModel> LoadSearchRecipes(string ingredientCategory, string ingredientCategory1)
{
    // select ingredient category to show results
    string sql = @"SELECT * FROM dbo.Recipe WHERE Ingredient1 IN('" + ingredientCategory.ToString() + "," + ingredientCategory.ToString() + "') AND WHERE Ingredient1 IN('" + ingredientCategory.ToString() + "," + ingredientCategory.ToString() + "');"; 

     return SqlDataAccess.LoadData<IngredientModel>(sql);
}
0vvn1miw

0vvn1miw1#

每个值中的一个值应在ingredient1和ingredient2中(不能同时在两者中)
在mysql中,您可以将这两个条件都作为整数计算,并确保求和为 1 :

where (ingredient1 = ?) + (ingredient2 = ?) = 1

实际上我怀疑你没有使用mysql。以下是其他数据库的标准方法:

where 
    (case when ingredient1 = ? then 1 else 0 end) 
    + (case when ingredient2 = ? then 1 else 0 end) = 1

问号应该替换为参数的值(bind参数的语法可能因数据库而异)。

相关问题