【问题标题】:Do a left join and sanitizing values at the same time?同时进行左连接和清理值吗?
【发布时间】:2020-07-13 18:14:25
【问题描述】:

考虑以下两个表:

table1

id    key
---------
1     foo


table2

id    key1    key2
------------------
1     foo     444
2     (foo)   453
3     bar     355

我想将两个表中的信息结合起来,如下:

select    t1.id, t1.key, t2.key2
from      [table1] t1
left join [table2] t2 on t1.[key] = t2.[key1]

结果

id    key    key2
-----------------
1     foo    444

问题是,我有时key1 中的值有括号(),但我需要忽略这些。所以实际上,(foo) 实际上也是foo,因此所需的输出是:

id    key    key2
-----------------
1     foo    444
2     foo    453

问题:我的查询应该如何完成?

【问题讨论】:

  • 旁白:使用 SQL Server 2017,您可以加入 on t1.[key] = Trim( '()' from t2.[key] ),但这并不完全正确。一次性清理可能就足够了,但'foo' 将匹配'(foo)'')foo(''foo('')foo)()()()'、...。

标签: sql sql-server tsql join sql-server-2012


【解决方案1】:

您可以只添加一个连接条件来处理由() 包围的值。想到in

select    t1.id, t1.key, t2.key2
from      [table1] t1
left join [table2] t2 on t2.[key1] in (t1.[key], '(' + t1.[key] + ')')

【讨论】:

    【解决方案2】:

    使用LTRIMRTRIM

       select    t1.id, t1.key, t2.key2
       from      [table1] t1
       left join [table2] t2 on
      RTRIM( LTRIM(t1.[key], '(') , ')' ) = 
        RTRIM( LTRIM(t2.[key], '(') , ')' )
    

    【讨论】:

    • 一个带有 3 个参数的 TRIM() 函数。它在文档中的什么位置?
    • 如果用户没有更多的代表,请不要只是开始显示答案总是以某种方式不正确。我看到 trim 在 oracle 中工作,我现在已经编辑了检查
    • 看到 trim 在 oracle 中工作,并且您认为 SQL Server 与 Oracle 相同。好吧,不是。
    • 我从没想过。那是我看到两个数据库都支持 TRIM 功能。不管我现在编辑了什么。
    猜你喜欢
    • 2014-12-10
    • 2012-12-21
    • 2013-03-03
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    相关资源
    最近更新 更多