SQL:使用一个 Table 作为对另一个 Table 的 'Like' 语句的输入

SQL: Use one Table as Input for a 'Like' Statement on Another Table

我有一个 sql 数据库,其中包含唯一 ID 和比赛名称,例如:

ID     CompetitionName
1      August Running Race
2      Running Race August
3      Running Race August
4      Running Race August.
5      Cycling Race
6      Cycling Race September

请注意,即使 CompetitionName 相同,每一行都有自己的 ID。

然后我有一个文件可以使用规则将这些比赛名称合并到合理的组中。规则可以是 'equals' 或 'contains'。包含规则意味着如果上面 table 中的 CompetitionName 以任何顺序包含 'RuleA' 下的内容和 'RuleB' 下的内容(如果 RuleB 不为空),那么我们应该采用我们新的 table 的竞争名称和 ID 以及第三列(竞争)应该从下方放置竞争条目。对于 equals 规则,标题必须与 RuleA 完全匹配。

RuleType   RuleA           RuleB     Competition
Contains   Running Race    August    August Running Race
Equals     Cycling Race              September Cycling Race

所以我想要的输出是:

ID     CompetitionName      Competition
1      August Running Race  August Running Race
2      Running Race August  August Running Race
3      Running Race August  August Running Race
4      Running Race August. August Running Race
5      Cycling Race         September Cycling Race

新的 table 不包括九月自行车赛,因为它不符合任何规则。

在我目前的代码中,我使用 like 语句一次执行一条规则:

select ID
from table1
where 
(CompetitionName LIKE '%Running Race%' and CompetitionName LIKE '%August%')

但是,我想从 table 中自动获取这些规则而不是输入它们,并且在规则适用时也从第二个 table 中获取相应的竞赛条目,所以我们有这些参赛作品的标准比赛名称。我将如何解决这个问题?如果您有解决其中一部分的任何想法,也请告诉我,因为它是构建的基础。

我不确定第一部分,但第二部分似乎是一个使用临时 table/table 变量存储标准比赛名称的存储过程。然后你可以select从它。

假设你在数据库中有一个rules table,你可以做

select t.ID, t.CompetitionName, r.competition
from table1 t, rules  
where CompetitionName like 
(case when ruletype = 'Contains' then '%' + RuleA + RuleB + '%' end)
or CompetitionName in (case when ruletype = 'Equals' then RuleA end)

但是,这不是理想的方法,您应该专注于更正 table 设计。