搜索以显示给定记录模式的精确匹配和最近匹配

时间:2012-10-11 14:24:29

标签: mysql sql

我在表格area中有一个字段property,在此字段中,记录保存在1-0-3-40-4-2-0中,依此类推。在每个记录中,1st表示区域的最高面额,第二个表示第二高,第三个 - 第三个最高和最后,即第四个表示区域的最低面额。格式x-x-x-x是我们国家的土地或财产区域的表示方式。

在上面的字段中搜索完全匹配不是问题,但如果我必须显示最接近匹配的结果,该怎么办呢。例如,1-0-3-31-0-4-41-0-3-5是与1-0-3-4

最接近的匹配

有可能吗?

由于

2 个答案:

答案 0 :(得分:2)

这是可能的,但很乱。如果您可以将“区域”字段标准化为单个列,这将有所帮助 - 这将使解决方案更整洁,更快!

示例实现可能是:

select area, 1 as match_quality
from property
where area = '1-0-3-4'
union
select area, 2 as match_quality
from property
where area like '1-0-3-_' 
union
select area, 3 as match_quality
from property
where area like '1-0-_-4' 

这假设区域之间的距离对于给定列中的任何值都是相同的。如果不是这种情况,您可以通过检索代码(通过SUBSTRING)并在其上执行您需要的任何算术来优化它。

如果将区域转换为单个列,这将变得更容易,更好,也更快(上述联合中的最后一个查询将会很慢,因为它无法有效地使用索引)。

例如:

select *, 1 as match_quality
from property
where area1 = 1
and area2 = 0
and area3 = 3
and area4 = 4
union 
select *, 2 as match_quality
from property
where area 1 = 1
and area 2 = 0
and area 4 = 4
union
select *, 3 as match_quality
from property
where area 1 = 1
and area2 = 0
and area4 = 4

答案 1 :(得分:1)

也许substring会帮助您:

select * 
from property
where SUBSTRING(area,1,3)=SUBSTRING('1-0-3-4',1,3)