在空值的情况下如何使用 like to return 数据

How to use like to return data also in case of empty values

我有一个 SQL script 其中 returns 3 个数据:ProductCategorySubcategory 我希望能够根据产品、类别和子类别从返回的列表中进行过滤。我需要始终使用过滤器中的所有三个项目。 我正在使用 Like 关键字 如果我仅用于过滤 ProductType 可以看出我有很多元素,其中 CategorySubcategory 为 null

但是如果我也为类别和子类别添加过滤器,如果我像屏幕截图中那样添加 like,我不会取回所有元素,(我认为在这种情况下我会得到与上一个屏幕截图相同的结果),但我得到了这个

我试过这样,

这里我想我会找回产品名称中有 's' 且类别中有 'b' 的所有项目,所以这将是预期的结果案例

你能告诉我如何使用 like 关键字来正确地完成这项工作吗?谢谢!

我想这就是你想要的

WHERE ProductType LIKE '%s%' AND Category LIKE '%b%'

此逻辑使您的结果错误,它使您得到具有“b”字符的类别 或者为空

Category LIKE '%b%' OR Category IS NULL

这是你拥有的:

where producttype like '%S%'
  and category like '%b%' or category is null
  and subcategory like '%%' or subcategory is null

但是 AND 优先于 OR,所以这转换为

where (producttype like '%S%' and category like '%b%')
   or (category is null and subcategory like '%%')
   or (subcategory is null)

因此,添加括号以获得您想要的内容:

where producttype like '%S%'
  and (category like '%b%' or category is null)
  and (subcategory like '%%' or subcategory is null)

混合使用 ANDOR 时应始终使用括号。