我试图从搜索字符串中返回人物,其中包含姓名的任何变体,例如:'john','john smith','smith,john','john jason smith'或任何其他常见的变异。如果需要,我可以清理字符串并格式化为正则表达式。
我的目标是类似于此:
SELECT firstname,
middlename,
lastname
FROM people
WHERE firstname LIKE 'search'
OR middlename LIKE 'search'
OR lastname LIKE 'search';
问题是像'john smith'这样的搜索字符串会返回所有 johns 和所有 smiths ,而不仅仅是 john smith 。有什么想法吗?
答案 0 :(得分:1)
如果您只想返回符合所有提供条件的行,则需要添加这些过滤条件。有几种方法可以做到,但你可以做一些简单的事情:
<强> SQL:强>
SELECT firstname,
middlename,
lastname
FROM people
WHERE ( Upper(firstname) LIKE token1
OR Upper(middlename) LIKE token1
OR Upper(lastname) LIKE token1 )
INTERSECT
SELECT firstname,
middlename,
lastname
FROM people
WHERE ( Upper(firstname) LIKE token2
OR Upper(middlename) LIKE token2
OR Upper(lastname) LIKE token2 );
答案 1 :(得分:0)
试试这个家伙。我针对SQL服务器测试了它,它可以工作。对其进行必要的更改以对抗Oracle。我只用1个字段名称对此进行了测试。只需编辑代码即可满足您的需求。它基本上只使用SQL实现了@Carth的解决方案。
DECLARE @stringsearch varchar(255)='stringvalue'
while CHARINDEX(' ',@stringsearch) > 1
begin
SET @stringsearch=REPLACE(@stringsearch,' ',' ')
end
SET @stringsearch=REPLACE(@stringsearch,' ','%'' AND fieldname LIKE ''%')+'%'''
DECLARE @sql varchar(max)=''
SET @sql='SELECT fieldname FROM TableName
WHERE fieldname Like ''%'+ @stringsearch
EXEC (@sql)
答案 2 :(得分:0)
考虑到你的特殊要求(与'john','john smith','smith,john','john jason smith'相匹配),这就是我的尝试:
SELECT firstname,
middlename,
lastname
FROM people
WHERE (firstname || ' ' || lastname) LIKE :search
OR (lastname || ', ' || firstname || ' ' || middlename) LIKE :search
OR (firstname || ' ' || middlename || ' ' || lastname) LIKE :search;
(为了清楚起见,我添加了括号,尽管在这种情况下不需要括号)