我一直在尝试计算以下几天。请帮助
PostgreSQL表:位置
Id State
--------------------
1 New York
2 Texas
input ='德克萨斯州对所有牛仔队的问候
输出:包含Texas的行
SELECT id, state FROM locations WHERE state ~* substring(input from state)
答案 0 :(得分:4)
1
select * from locations where 'Greetings from Texas to all Cowboys' ~ State;
2
select * from locations where State = any(string_to_array('Greetings from Texas to all Cowboys',' '));
上述两种方法在某些情况下都存在一些问题。但我想知道它们是否适合你。
3
select * from locations where 'reetings from Texas to all Cowboys' ~* ('\\m' || state || '\\M');
最后一种方法会更好。
答案 1 :(得分:2)
搜索词不是模式。试试这个:
select * from locations where 'Hello from Texas!' like '%' || state || '%';
或者这个:
select * from locations where 'Hello from Texas!' ~* ('.*' || state || '.*');
如果你想要Posix正则表达式。
示例:
# create table locations(id integer, state text);
CREATE TABLE
# insert into locations values (1,'New York'),(2,'Texas') ;
INSERT 0 2
# select * from locations where 'Hello from Texas!' like '%' || state || '%';
id | state
----+-------
2 | Texas
(1 row)
# select * from locations where 'Hello from Texas!' ~* ('.*' || state || '.*');
id | state
----+-------
2 | Texas
(1 row)
# select * from locations where 'Greetings from you ex' like '%' || state || '%';
id | state
----+-------
(0 rows)
# select * from locations where 'Greetings from your ex' ~* ('.*' || state || '.*');
id | state
----+-------
(0 rows)
如果您需要检测字边界,这需要一些改进或过程:
# select * from locations where 'fakulos greekos metexas' ~* ('.*' || state || '.*');
id | state
----+-------
2 | Texas
如果您在搜索词中有正则表达式元字符(请参阅PostgresSQL文档作为列表),那么您可能需要先引用它们。这看起来有点奇怪,但这就是逃避总是看起来像:
select regexp_replace('Dont mess (with) Texas, The Lone *',E'([\(\)\*])',E'\\\\\\1','g');
([\(\)\*])
是您要转义的字符列表。
但是,如果从不在搜索词中需要正则表达式,那么使用简单的字符串搜索功能(如strpos()可能更容易:
select strpos('Dont mess (with) Texas','Texas')>0;
?column?
--------
t
select strpos('Dont mess (with) Texas','Mars')>0;
?column?
--------
f
如果您需要不区分大小写的比较
,则可以使用upper()
select strpos(upper('Dont mess (with) Texas'),upper('teXas'))>0;
?column?
--------
t
答案 2 :(得分:1)
我会看一下全文搜索:
SELECT
id,
state
FROM
locations
WHERE
to_tsvector('english', 'Greetings from Texas to all Cowboys') @@ plainto_tsquery('english', state);
标准版本从8.3版本开始,在旧版本中,您必须从contrib。
安装tsearch2http://www.postgresql.org/docs/current/interactive/textsearch.html