2010-08-04 73 views

回答

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',' ')); 

两种方法上面都有一些circumstances.But一些问题,我想知道他们是否适合你。

3.

select * from locations where 'reetings from Texas to all Cowboys' ~* ('\\m' || state || '\\M'); 

最后一个方法会比较好。

+0

谢谢你们。它在一张小桌子上完美运作。但不是在包含1百万个位置的巨大桌子上。我认为,这是索引问题 感谢您的快速反应 – Joey 2010-08-04 09:10:20

+1

如果你想这个快速的大表,那么你需要特殊的索引和其他魔法。请参阅http://www.postgresql.org/docs/8.4/static/textsearch.html如何快速进行索引全文搜索。 – 2010-08-04 09:12:28

+0

我发现了为什么我有一个问题。 colunm状态的某些行有一些括号。 从状态如'%(%')返回与行排列的位置的状态选择状态 如何在状态 – Joey 2010-08-04 11:06:36

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 

如果你有正则表达式,元字符(请参阅为列表中的PostgreSQL的文档)在你的搜索词中,那么你可能需要先引用他们。这看起来有点怪异,但是这是永远逃避的样子:

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 
+0

像“从你的前问候”输入将返回一个匹配“得克萨斯”。 – Joey 2010-08-04 08:29:20

+0

我也尝试POSIX,但得到以下错误 错误:无效的正则表达式:括号()不平衡 SQL状态:2201B – Joey 2010-08-04 08:34:07

+0

我已经添加了我输入的脚本来验证我不是告诉你bullsh * t。检查你的语法。 – 2010-08-04 08:38:34