从第一个表中获取所有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中。
为避免您搜索'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, ' %')
使用join和like进行匹配
select u.* from table_users u join table_name b on
u.users like concat('%',b.name,'%')
您可以使用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 + ' %'
);