2011-03-09 38 views
1

给出一个数据表,其中包含列id,颜色,大小以及第二个包含规则/模式以及rule_id,color_condition和size_condition的表。用于从数据表和模式表生成匹配的SQL

因此,一个基本规则将RULE_ID = 1,颜色为蓝色,大小=任何或RULE_ID = 2,颜色为蓝色,大小= 15

我如何构建产生比赛进入第三个SQL查询表

例如,对于在数据表ID的条目= 1,颜色=蓝色,大小= 10条两个规则将适用及其所用的匹配表将cotain两个条目

rule_id=1, entry_id=1 
rule_id=2, entry_id=1 

如何通过周期模式以及如何构建匹配以便它可以处理通配符或省略co如果它们是空的。

请提供说明或关键字,我随时可以阅读。

回答

1

比方说,你有规则表:

Rule 
Id--Color--Size 
1 --blue -- null 
2 --blue -- 15 

和入境表

Entry 
Id--Color--Size 
1 --blue -- 10 

将一个空值,而不是一个“任意”值,以保持一定的强类型

一解决方案:

Select r.id as rule_id, 
     e.id as entry_id 
From Entry e inner join Rule r 
      On (e.Color = r.Color or r.Color is null) 
      And (e.Size <= r.Size or r.Size is null) 

你可以有更好的表现创建新表颜色:

Color 
Id--Name 
1 --Red 
2 --Blue 

Rule 
Id--Id_Color--Size 
1 -- 2  -- null 
2 -- 2  -- 15 

Entry 
Id--Id_Color--Size 
1 -- 2 -- 10 

Select r.id as rule_id, 
     e.id as entry_id 
From Entry e inner join Rule r 
    On (e.Id_Color = r.Id_Color or r.Color is null) 
    And (e.Size <= r.Size or r.Size is null) 

添加一个索引到两个Id_Colors