繁体   English   中英

如何在同一行的SQL中使用LIKE或CONTAINS子句?

[英]How do I use a LIKE or CONTAINS clause in SQL on the same row?

在我的项目中,您可以列出您拥有的成分并搜索可以用这些成分制成的食谱。 这是我的示例SQL查询:这是我想要获取匹配列表的数据库https://i.imgur.com/LgZ0WMD.png

SELECT recipes_Name 
FROM tblrecipes
INNER JOIN tblingredients
ON tblrecipes.recipes_ID = tblingredients.ingredients_ID
WHERE ingredients_name = variable1 AND variable2 AND variable3

为什么此查询不起作用?

您可以使用in子句:

SELECT recipes_Name 
FROM tblrecipes
INNER JOIN tblingredients
ON tblrecipes.recipes_ID = tblingredients.ingredients_ID
WHERE ingredients_name in (variable1, variable2, variable3)

我的建议是通过安全性将准备好的语句与PDO一起使用。

更新:

我进行了查询,将仅获取指定了所有成分的食谱(即使食谱中缺少一种成分,也不会包含在内):

select
    rcp.*,
    ingr.selected_ingr_count
from
    tblrecipes rcp inner join(
        select
            ingredients_ID as recipe_id,
            count(*) as selected_ingr_count
        from
            tblingredients
        where
            ingredients_name in(
                'egg',
                'butter',
                'milk',
                'flour'
            )
        group by
            ingredients_ID
    ) as ingr on
    ingr.recipe_id = rcp.recipes_ID
    and ingr.selected_ingr_count =(
        select
            count(*)
        from
            tblingredients
        where
            tblingredients.ingredients_ID = rcp.recipes_ID
    )

这将导致:

recipes_ID      recipes_Name        selected_ingr_count
        1       cake                3
        3       brownies            2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM