我试图创建一个查询,将返回在特定列中包含确切字符串的所有内容。当我搜索create
或query
时,它应该返回x = "create query"
,但当我搜索reate
或uer
时,它不返回任何东西。
我需要等效的:
select *
from table
where column_name ~* ycreatey
以及我将用传递的参数替换create的地方。如果我硬编码值,我看到这是有效的,但我无法从方法传递它,这是我尝试的代码:
@Select({SELECT * from table where column_name ~* '\y' || #{valuePassedFromMethod} || '\y'"})
List<String> methodName(@Param("valuePassedFromMethod") String valuePassedFromMethod);
我没有太多的经验,我无法找到问题,如果有人能帮助我解决这个问题,我将不胜感激。
这里的问题是表达式column_name ~* '\y' || #{valuePassedFromMethod} || '\y'
是从左到右求值的,因为所有操作符都具有相同的优先级。您可以在这里看到,所有涉及的操作符都属于"所有其他本地和用户定义的操作符"。
column_name ~* '\y'
返回true,随后的连接返回一个文本。因此,您的查询最终看起来像SELECT * FROM unl_unit WHERE 'truecreatey'
,假设您正在寻找字符串create
。现在您可以看到WHERE子句实际上是如何抱怨接收到文本而不是布尔值的。您可以简单地将搜索模式用圆括号括起来以避免这种情况。
@Select({SELECT * from table where column_name ~* '(\y' || #{valuePassedFromMethod} || '\y')"})
List<String> methodName(@Param("valuePassedFromMethod") String valuePassedFromMethod);
话虽如此,我不认为你正在使用的正则表达式实际上反映了你想要实现的搜索。y表示字符串的开始/结束,所以你实际上是在搜索确切的字符串'create'。如果您想搜索包含create
的字符串,您应该执行以下操作:
SELECT * FROM unl_unit WHERE unlun_name like '%' || 'create' || '%';
方法是:
@Select({SELECT * from table where column_name LIKE '%' || #{valuePassedFromMethod} || '%'"})
List<String> methodName(@Param("valuePassedFromMethod") String valuePassedFromMethod);
注意,这里甚至不需要括号,因为LIKE操作符的优先级低于连接操作符。