2010-08-04 69 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