【问题标题】:compare strings of uneven length in TSQL比较 SQL 中长度不等的字符串
【发布时间】:2016-02-04 23:11:15
【问题描述】:

我有两张桌子。它们都包含(荷兰)邮政编码。 它们的格式为 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-

所以我必须根据表中邮政编码的长度来连接这两个表。

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

【问题讨论】:

  • 你说的太对了,我编辑了。对不起。好像你比我更了解这个问题:)

标签: sql sql-server tsql sql-server-2012 string-comparison


【解决方案1】:

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

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

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

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中有多个匹配,返回最佳匹配。

【讨论】:

  • 这就是我最终实现它的方式。
【解决方案2】:

你可以使用:

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

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

在你加入搜索条件。

【讨论】:

  • 有两个不同的表。为此,我应该先加入他们,对吧?
【解决方案3】:

您可以使用LEFT(column,4)

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

【讨论】:

  • 如果右列包含 1234A,那么 1234 不应该是命中,1234b 也不应该是命中。如果您只比较前 4 个,就会存在这种风险。
【解决方案4】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 2020-12-07
    • 2020-02-04
    • 2018-05-11
    • 1970-01-01
    相关资源
    最近更新 更多