2015-11-04 68 views
2

我有两个表。他们都包含(荷兰)邮政编码。 那些格式为9999AA并存储为varchar(6)。 左表中的代码是完全比较TSQL中不均匀长度的字符串

John Smith  1234AB 
Drew BarryMore 3456HR 
Ted Bundy   3456TX 
Henrov   8995RE 
My mother   8995XX 

在右表中的代码可以是不完整的

1234AB Normal neigbourhood 
3456 Bad neighbourhood 
8995R Very good neighbourhood 

我需要加入对postalcodes这些表。在这个例子中,输出必须是

John Smith  Normal neighbourhood 
Drew BarryMore Bad neighbourhood 
Ted Bundy   Bad neighbourhood 
Henrov   Very good neighbourhood 
My mother   -unknown- 

所以我要加入基于邮政编码在表长度的两个表。

有关如何做到这一点的任何建议?我只能拿出在ON语句的情况,而且这是没有那么聪明;)

+0

妳如此吧,我编辑过。抱歉。似乎你比我更了解这个问题:) – Henrov

回答

3

如果你在第二个表中没有“重复”,你可以使用like

select t1.*, t2.col2 
from table1 t1 join 
    table2 t2 
    on t1.postalcode like t2.postalcode + '%'; 

但是,这不会是有效的。相反,在table2(postalcode)指数等一系列left join s是可能更快:

select t1.*, coalesce(t2a.col2, t2b.col2, t2c.col2) 
from table1 t1 left join 
    table2 t2a 
    on t2a.postalcode = t1.postalcode left join 
    table2 t2b 
    on t2b.postalcode = left(t1.postalcode, len(t1.postalcode) - 1) left join 
    table2 t2c 
    on t2c.postalcode = left(t1.postalcode, len(t1.postalcode) - 2) 

这可以在table2(postalcode)采取指数的优势。此外,即使在table2中有多个匹配时,它也只返回一行,返回最佳匹配。

+0

这就是我到底如何实现它的。 – Henrov

1

您可以使用:

on '1234AB' like '1234'+'%' 

on firstTable.code like secondTable.code+'%' 

在你加入搜索条件。

+1

有两个不同的表格。为了这个工作,我应该先加入他们? – Henrov

2

使用JOIN

查询

SELECT t1.col1 as name, 
     coalesce(t2.col2,'-unknown-') as col2 
FROM table_1 t1 
LEFT JOIN table_2 t2 
ON t1.pcode LIKE t2.col1 + '%'; 

SQL Fiddle

1

可以使用LEFT(column,4)

select t1.*, t2.col2 
from table1 t1 join 
    table2 t2 
    on LEFT(t1.postalcode,4)=t2.postalcode 
+0

如果右栏包含1234A,那么1234不应该是命中,1234b也不会命中。如果你只比较前4个,那么风险就在那里。 – Henrov