比较SQL中长度不均匀的字符串

compare strings of uneven length in TSQL

我有两个 table。它们都包含(荷兰)邮政编码。 它们的格式为 9999AA 并存储为 varchar(6)。 左边table代码完整

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

右边table代码可能不完整

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

我需要加入这些 table 的邮政编码。在此示例中,输出必须为

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

所以我要根据右边table.

中邮编的长度把两个table拼接起来

关于如何做到这一点有什么建议吗?我只能在 ON 语句中想出一个 CASE 但这不是很聪明 ;)

您可以使用:

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

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

在你加入搜索条件。

如果你在第二个table中没有"duplicates",你可以使用like:

SELECT t1.*, t2.col2
FROM table1 AS t1
JOIN table2 AS t2
ON t1.postalcode LIKE t2.postalcode + '%';

但是,这不会有效。相反,table2(postalcode) 和一系列 LEFT JOIN 上的索引可能更快:

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) 上的索引。此外,它只有 returns 一行,即使 table2 中有多个匹配项,也返回最佳匹配项。

使用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

您可以使用LEFT(column,4)

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