选择与其他表匹配的所有行

问题描述 投票:0回答:3

从第一个表中获取所有Users,在另一个表中有任何单词匹配;

我有Users表,其中包含与FullName列,该列是Full Text Search索引。有时候第一个“单词”是名字,有时候第一个“单词”是来自FullName列的姓氏;

像约翰史密斯或史密斯约翰。

另一个只有本地名字的表。

我想让所有具有匹配本地名称的用户。

Users Table:
John Smith
Rebecca Mark
Maria Anna
Lance Maria 
Emilia Clark
Snow John
Natalie Butler

Name Table:
Maria
Smith

Result of Query:
John Smith
Maria Anna
Lance Maria
Snow John

我只能使用包含功能的单个名称。

SELECT * FROM Users WHERE CONTAINS(FullName, 'John');

但我需要在Name Table的每一行。

来自FullName的每一行都包含任何Name Table ......但是在SQL Query中。

sql sql-server
3个回答
1
投票

为避免您搜索'Maria'且匹配名称为'Marianne'的情况, 检查2个条件:(1)名称在开头或(2)在FullName结束时:

(1):

SELECT u.* 
FROM Users u INNER JOIN Name n
ON 
  u.FullName LIKE concat(n.name, ' %') 
  OR 
  u.FullName LIKE concat('% ', n.name)

或(2):

SELECT u.* 
FROM Users u INNER JOIN Name n
ON 
  concat(' ', u.FullName, ' ') LIKE concat('% ', n.name, ' %') 

1
投票

使用join和like进行匹配

select u.* from table_users u join table_name b on
             u.users like concat('%',b.name,'%')

1
投票

您可以使用exists

select u.*
from users u
where exists (select 1
              from nametable n
              where u.fullname like '%' + n.name + '%'
             );

如果要避免对名称进行部分匹配,请考虑分隔符:

where exists (select 1
              from nametable n
              where ' ' + u.fullname + ' ' like '% ' + n.name + ' %'
             );
© www.soinside.com 2019 - 2024. All rights reserved.