问题描述
在 sql server 中,如果我执行以下操作:
in sql server, if i do the following:
difference ('kennady', 'kary') : i get 2
如果我这样做:
difference ('kary', 'kennady') : i get 3.
我认为差异函数会查看底层的 soundex 值,并给出一个 0-4 的数字,表示有多少字符是相同的.
i thought the difference function looks at the soundex values under the hood, and gives a 0-4 number of how many characters in place are the same.
select soundex('kennady') as [soundex kennady] , soundex('kary') as [soundex kary] , difference ('kennady', 'kary') as [difference kennady vs kary] , difference ('kary', 'kennady') as [difference kary vs kennady];
推荐答案
这是严格的观察.文档 非常清楚:
this is strictly observational. the documentation is pretty clear:
返回的整数是 soundex 值中的字符数那是一样的.返回值范围从 0 到 4:0表示弱相似或无相似,4 表示强相似或相同的值.
the integer returned is the number of characters in the soundex values that are the same. the return value ranges from 0 through 4: 0 indicates weak or no similarity, and 4 indicates strong similarity or the same values.
根据本文档,返回值不应因参数的顺序而异.
according to this documentation, the return value should not differ based on the order of the arguments.
来自我的查询:kennady"--> k530 和kary"--> k600.它们有两个共同的字符,所以值应该是 2.
from my queries: "kennady" --> k530 and "kary" --> k600. these have two characters in common, so the value should be 2.
现在,我注意到kenn"--> k500.将kennady"截断为kary"的长度会得到值3".嗯.
now, i notice that "kenn" --> k500. truncating "kennady" to the length of "kary" results in the value "3". hmmm.
因此,我认为 difference() 是使用第一个参数的长度来截断第二个参数.这使得参数的顺序很重要.先把较长的论点放在首位.
hence, i think that difference() is using the length of the first argument to truncate the second argument. that makes the order of the arguments important. put the longer argument first.
我在其他一些字符串上试过这个.相同的模式似乎有效.我还没有找到任何说明这种情况的文件.
i tried this out on some other strings. the same patterns seems to work. i have not found any documentation that specifies that this is the case.
我想微软会称其为功能"而不是错误";)
i suppose microsoft would call this a "feature" and not a "bug" ;).
以上推测并不完全正确.考虑以下
the above speculation is not quite correct. consider the following
- leepaupauld --> l114
- 利奥波德 --> l143
- leepaup --> l110
然而,
- difference(leepaupauld, leopold) = 4 (!)
- 差异(利奥波德,利波保德)= 3
- difference(leepaup, leopold) = 3 (!)
- 差异(利奥波德,利帕普)= 2
考虑到字符串的 soundex 值,(!) 是我的判断,即结果根本没有意义.
the (!) is my judgement that the result makes no sense at all, given the soundex values for the strings.
所以,问题不在于长度.这是@jpw 在评论中指向的底层方法.问题似乎是一个字符串中的重复匹配值.但是,根据文档,这些不应该多次匹配同一个字符.
so, the issue isn't the length. it is the underlying method, which @jpw points to in the comment. the problem appears to be duplicate matching values in one string. however, according to the documentation, these should not match the same character multiple times.
我的建议:使用 levenshtein 距离.这说得通.它在更长的字符串上效果更好.这是理智的.它不是内置的,但很容易在网络上找到任何数据库的实现.
my advice: use levenshtein distance. it makes sense. it works better on longer strings. it is sane. it is not built in, but it is easy enough to find an implementation on the web for any database.