【问题标题】:SQL Join with wildcards使用通配符连接 SQL
【发布时间】:2014-12-28 19:34:24
【问题描述】:

假设我有两个表:table1如下

Name     |Surname| col1
------------------------
 Bob     |Smith  | BS1
Mary Jane|Jones  | MJ1

和table2如下:

Name     |Surname       | col2
------------------------------
 Bob     |Keller Smith  | BS2
Mary     |Jones         | MJ2

我想要将这些连接在一起以获得:

Name     |Surname       | col1| col2
-------------------------------------
 Bob     |Keller Smith  | BS1 | BS2
Mary     |Jones         | MJ1 | MJ2

我试过了:

SELECT tableb.Name, tableb.Surname, tablea.col1, tableb.col2
FROM table1 as tablea
LEFT JOIN table2 as tableb
ON '%'+tablea.Name+'%' LIKE '%'+tableb.Name+'%' AND '%'+tablea.Surame+'%' LIKE '%'+tableb.Surame+'%'

但这些似乎加入了一切。

如何使用通配符正确连接列?

【问题讨论】:

  • 你想要一个 INNER JOIN。
  • @Tomalak 我刚试了一下,得到了相同的输出。
  • (i) LIKEs 左侧的 '%' 很可能是多余的(充其量) - 但绝对不会被 LIKE 运算符评估为占位符。 (ii) “Bob”前面的空格是故意的吗?

标签: sql join


【解决方案1】:

试试这个:

SELECT tableb.Name, tableb.Surname, tablea.col1, tableb.col2
FROM table1 as tablea
LEFT JOIN table2 as tableb
    ON (tablea.Name LIKE '%' + tableb.Name + '%' OR tableb.Name LIKE '%' + tablea.Name + '%')
    AND (tablea.Surname LIKE '%' + tableb.Surname + '%' OR tableb.Surname LIKE '%' + tablea.Surname + '%')

【讨论】:

  • 这不起作用:我得到了 ` Name Surname col1 col2 1 BS1 2 MJ1 `
  • 我刚刚试了一下,它返回的输出完全符合您的预期。
  • 哦,这可能是 MySQL 或 SQLite 的问题吗?
  • 我在R中使用sqldf函数。
  • 我不认识他们。我只能说这适用于 SQL Server,应该适用于 MySQL。
【解决方案2】:

我想你想要一个INNER JOIN

另请注意,百分号只能在 LIKE 运算符的右侧识别。加入NameSurname 似乎也不对

SELECT 
  a.Name, b.Surname, a.col1, b.col2
FROM 
  table1 AS a
  INNER JOIN table2 AS b ON 
    a.Name LIKE '%' + b.Name + '%'
    OR b.Name LIKE '%' + a.Name + '%'

【讨论】:

  • @Tomalek 你的名字和姓氏是正确的。我会相应地编辑我的问题。
  • 这不起作用:我得到了[1] Name Surname col1 col2 <0 rows> (or 0-length row.names)
【解决方案3】:

对于您的示例数据,以下任一方法都有效:

SELECT tableb.Name, tableb.Surname, tablea.col1, tableb.col2
FROM table1 as tablea
INNER JOIN table2 as tableb
ON tablea.Name LIKE '%'+tableb.Name+'%'
  AND tableb.Surname LIKE '%'+tablea.Surname+'%';

SELECT tableb.Name, tableb.Surname, tablea.col1, tableb.col2
FROM table1 as tablea
INNER JOIN table2 as tableb
ON CHARINDEX(tableb.Name, tablea.Name) > 0
  AND CHARINDEX(tablea.Surname, tableb.Surname) > 0;

SQL Server Fiddle 和(调整了串联,INSTR 接管CHARINDEX)在SQL Lite Fiddle
后一个版本的性能可能会更好,尤其是在可以使用索引时(至少在某些数据库系统中),LIKE 运算符会忽略索引。

【讨论】:

    猜你喜欢
    • 2015-10-19
    • 2014-04-29
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2015-10-11
    • 1970-01-01
    • 2015-02-24
    相关资源
    最近更新 更多