我有一张这样的 table
Rules (RuleValue varchar (50))
它的值如下
A1B1C1
A1B1C0
A1B0C0
还有一张 table
Input (RulePart varchar (2))
它可以有如下值:
A1
B1
C1
我想获取所有 RuleValues,其中所有 RulePart 都匹配 RuleValue 中的任何位置 以下是硬编码 RulePart 的示例:
Select RuleValue from Rules where Rules.RuleValue like '%A1%' and Rules.RuleValue like '%B1%' and Rules.RuleValue like '%C1%'
对于上面的示例,我的预期结果是 A1B1C1 或 B1A1C1 或 C1A1B1 等。
我尝试使用 inner join,但它并没有匹配每一行中的所有规则部分。
我可以通过动态创建查询来实现这一点,但我不想这样做,除非它会影响查询性能。
最佳答案
一种方法是:
Select r.RuleValue
from Rules r
join Input i
on r.RuleValue like '%' + i.RulePart + '%'
group by r.RuleValue
having count(distinct i.RulePart) = 3 -- or (select count(*) from Input )
更新
更优雅的方式是使用NOT EXISTS
来代表ALL
select *
from Rules r
where not exists
(
select *
from Input i
where r.RuleValue not like '%'+i.RulePart+'%'
)
关于SQL 查询以选择在另一个表的字段中具有匹配子字符串的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27014195/