我试图找出什么是最优化的SQL查询来实现以下。SQL Server最佳匹配查询与更新(T-SQL)
我有一个包含邮编/ PostalCodes一个表,让我们假设以下结构:
table_codes:
ID | ZipCode
---------------
1 1234
2 1235
3 456
等。
我的应用程序的用户填写了他们需要输入他们的邮编(邮编)的轮廓。 假设有时,用户将进入我的表没有定义一个邮编,我想根据用户输入的zip建议最佳匹配。
我使用下面的查询:
Declare @entered_zipcode varchar(10)
set @entered_zipcode = '23456'
SELECT TOP 1 table_codes.ZipCode
FROM table_codes
where @entered_zipcode LIKE table_codes.ZipCode + '%'
or table_codes.ZipCode + '%' like @entered_zipcode + '%'
ORDER BY table_codes.ZipCode, LEN(table_codes.ZipCode) DESC
基本上,我想以下几点:
如果@entered_zipcode长于表中的任何邮政编码,我想以获得匹配@entered_zipcode的zip表中的最佳前缀如果@entered_zipcode比表中的任何现有代码都短,我试图在匹配@entered_zipcode的zip表中获得最佳前缀
在表中使用它作为前缀,并得到最佳匹配
此外,我建立一个临时表结构如下:
#tmpTable
------------------------------------------------------------------------------------
ID | user1_enteredzip | user1_bestmatchzip | user2_enteredzip | user2_bestmatchzip |
------------------------------------------------------------------------------------
1 | 12 | *1234* | 4567 | **456** |
2 |
3 |
4 |
进入拉链是用户输入一个和* .. *之间的代码是我查找表中最匹配的代码,我试图使用下面的查询。
查询时间似乎有点长,这就是为什么我在优化它求助:
update #tmpTable
set user1_bestmatchzip = (SELECT TOP 1
zipcode
FROM table_codes
where #tmpTable.user1_enteredzip LIKE table_codes.zipcode + '%'
or table_codes.zipcode + '%' like #tmpTable.user1_enteredzip + '%'
ORDER BY table_codes.zipcode, LEN(table_codes.zipcode) DESC
),
user2_bestmatchzip = (SELECT TOP 1
zipcode
FROM table_codes
where #tmpTable.user2_enteredzip LIKE table_codes.zipcode + '%'
or table_codes.zipcode + '%' like #tmpTable.user2_enteredzip + '%'
ORDER BY table_codes.zipcode, LEN(table_codes.zipcode) DESC
)
from #tmpTable
你为什么使用临时表? – vulkanino 2012-02-29 12:57:19
我正在尝试使用该临时表进行一些计算。我想展示的是,我需要在一次更新操作中为2列获得最佳匹配zip。在我看来,我的查询不是最理想的方式。 – mmmmmm 2012-02-29 13:07:25