我有两个桌子。它们都包含(荷兰)邮政编码。它们的格式为9999AA,并存储为varchar(6)。在左表中,代码是完整的
John Smith 1234AB
Drew BarryMore 3456HR
Ted Bundy 3456TX
Henrov 8995RE
My mother 8995XX
在右表中,代码可能不完整
1234AB Normal neigbourhood
3456 Bad neighbourhood
8995R Very good neighbourhood
我需要在邮政编码上加入这些表格。在此示例中,输出必须为
John Smith Normal neighbourhood
Drew BarryMore Bad neighbourhood
Ted Bundy Bad neighbourhood
Henrov Very good neighbourhood
My mother -unknown-
所以我必须根据right表中邮政编码的长度将两个表连接起来。
关于如何执行此操作的任何建议?我只能在ON语句中提出一个CASE,但这不是那么聪明;)
如果第二张表中没有“重复项”,则可以使用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)
上的索引。另外,即使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 + '%';
您可以使用LEFT(column,4)
select t1.*, t2.col2
from table1 t1 join
table2 t2
on LEFT(t1.postalcode,4)=t2.postalcode
您可以使用:
on '1234AB' like '1234'+'%'
on firstTable.code like secondTable.code+'%'
在您加入时搜索条件。