MySQL 连接两个只有部分匹配的表

MySQL joining two tables with only a partial match

我正在为社区中的尼泊尔难民做一些志愿者工作,我正在尝试整理他们的地址。我在一个 table 中有 656 个尼泊尔姓氏,在另一个 table 中有大约 608,000 个地址。我以前从未使用过 MySQL 并且只是在网上学习了一些来制作这些 table。 来自 table 的非真实姓名。 我的 tables:

AddressTable: 4 Columns

Owner_Name      Owner_Address   Owner_CityState   Owner_Zip
------------------------------------------------------
Smith, John   | ************* | *************** | *****
adhikari, Prem| ************* | *************** | *****
Baker, Mary   | ************* | *************** | *****

NamesTable: 1 Column

Last_Name
-----------
Smith
adhikari
Baker

我只想要拥有尼泊尔姓氏的人的地址,所以我想 select 通过加入 table 我的 AddressTable 中与我的 NamesTable 中的姓氏相匹配的所有列s 来自 NamesTable 中的 Last_Name 列和 AddressTable 中的 Owner_Name 列。由于 Owner_Name 列同时具有姓氏和名字,因此我在执行此操作时遇到了麻烦。

我推荐在这里使用REGEXP

SELECT at.*
FROM AddressTable at
INNER JOIN NamesTable nt
    ON at.Owner_Name REGEXP CONCAT('^', nt.Last_Name, ',');

Demo

正如上面评论中提到的,给定的姓氏本身可能不是唯一的。我们可以修改上面的查询来检查名字,假设名字 table 也包含:

SELECT at.*
FROM AddressTable at
INNER JOIN NamesTable nt
    ON at.Owner_Name REGEXP CONCAT('^', nt.Last_Name, ',') AND
       at.Owner_Name REGEXP CONCAT(' ', nt.First_Name, '$');

但即使这样可能仍然存在问题,因为有时人们的名字或姓氏由两个(或更多)单词组成。另外,中间名之类的东西也是可以的。

为了更好的解决方案,您可能希望在将数据导入数据库之前将名字、中间名和姓氏分成单独的列。

在我回答之前,我只想说,这十有八九是行不通的。像这样的名称匹配充满了问题,除非您知道数据是规范结构的。

您可以通过多种方式做到这一点。这个想法是您需要 on 子句中的函数。例如:

select . . . 
from addresstable a join
     namestable n
     on n.last_name = substring_index(owner_name, ',', 1);

这假定姓氏在第一个逗号之前的 owner_name 中。