使用 MySQL 比较两个字符串

发布于 2024-09-06 08:17:20 字数 665 浏览 3 评论 0原文

我不想比较 SQL 请求中的两个字符串,以便检索最佳匹配,目的是向操作员建议可能的最佳邮政编码。 例如,在法国,我们有整数邮政编码,所以我提出了一个简单的请求:

SELECT *
FROM myTable
ORDER BY abs(zip_code - 75000)

此请求首先返回最接近巴黎的数据。

不幸的是,英国有AB421RS这样的邮政编码,所以我的请求无法实现。 我在 SQL Server 中看到一个函数“差异”: http://www .java2s.com/Code/SQLServer/String-Functions/DIFFERENCEworkoutwhenonestringsoundssimilartoanotherstring.htm

但我使用 MySQL..

有没有人有一个好主意可以通过一个简单的请求来完成这一任务?

PS:编辑距离不会这样做,因为我真的不想像数字一样比较字符串。 ABCDEF 必须比 ZBCDEF 更接近 AWXYZ。

I wan't to compare two strings in a SQL request so I can retrieve the best match, the aim is to propose to an operator the best zip code possible.
For example, in France, we have Integer Zip code, so I made an easy request :

SELECT *
FROM myTable
ORDER BY abs(zip_code - 75000)

This request returns first the data closest of Paris.

Unfortunatelly, United Kingdom have zip code like AB421RS, so my request can't do it.
I see in SQL Server a function 'Difference' : http://www.java2s.com/Code/SQLServer/String-Functions/DIFFERENCEworkoutwhenonestringsoundssimilartoanotherstring.htm

But I use MySQL..

Is there anyone who have a good idea to do the trick in one simple request ?

PS : the Levenshtein Distance will not do it, as I really wan't to compare string like if they were number. ABCDEF have to be closer to AWXYZ than to ZBCDEF.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

春花秋月 2024-09-13 08:17:20

好吧,我必须停止提问并立即找到答案!

对于社区,我将做以下事情:

select *
from myTable
order by abs(ascii(substring(zip_code,1,1)) - ascii(substring('AAAAA',1,1))) asc,
         abs(ascii(substring(zip_code,2,1)) - ascii(substring('AAAAA',2,1))) asc,
         abs(ascii(substring(zip_code,3,1)) - ascii(substring('AAAAA',3,1))) asc,
         abs(ascii(substring(zip_code,4,1)) - ascii(substring('AAAAA',4,1))) asc,
         abs(ascii(substring(zip_code,5,1)) - ascii(substring('AAAAA',5,1))) asc

Ok, I have to stop asking question and find answer just after !!

For the community, here is what I will do :

select *
from myTable
order by abs(ascii(substring(zip_code,1,1)) - ascii(substring('AAAAA',1,1))) asc,
         abs(ascii(substring(zip_code,2,1)) - ascii(substring('AAAAA',2,1))) asc,
         abs(ascii(substring(zip_code,3,1)) - ascii(substring('AAAAA',3,1))) asc,
         abs(ascii(substring(zip_code,4,1)) - ascii(substring('AAAAA',4,1))) asc,
         abs(ascii(substring(zip_code,5,1)) - ascii(substring('AAAAA',5,1))) asc
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文