2011-11-16 91 views
0

這個問題的第二部分:查找匹配

注:我運行的Postgres 7.4,是的,我們正在升級

示例數據

address   | zip 
-----------------------+-------------+ 
123 main street  | 12345 
-----------------------+-------------+ 
23 where road   | 12345 
-----------------------+-------------+ 
South 23 where lane | 12345 

查詢

SELECT address 
FROM tbl 
WHERE zip = 12345 
AND LOWER(substring(address, '^\\w+')) = LOWER('lane') 

也試過

SELECT address 
FROM tbl 
WHERE zip = 12345 
AND LOWER(substring(address, '\\w+')) = LOWER('lane') 

SELECT address 
FROM tbl 
WHERE zip = 12345 
AND LOWER(substring(address, '^\\w')) = LOWER('lane') 

SELECT address 
FROM tbl 
WHERE zip = 12345 
AND LOWER(substring(address, '\\w')) = LOWER('lane') 

我想是能夠搜索在地址欄中的地址的任何部分。因此,如果我需要所有包含lane這個詞的行,我可以通過lane和zip返回所有行。這會給我:

address   | zip 
-----------------------+-------------+ 
South 23 where lane | 12345 

或者,如果我需要的所有行和23個地址,這會給我:

address   | zip 
-----------------------+-------------+ 
23 where road   | 12345 
-----------------------+-------------+ 
South 23 where lane | 12345 

有什麼我可以在例如查詢更改上面允許這個?

回答

1

這取決於你所說的「所有具有單詞通道的行」的含義。一個正則表達式可能不會在這裏工作。

with tbl as (
    select '123 main street' address, '12345' zip 
    union all 
    select '23 where road', '12345' zip 
    union all 
    select 'South 23 where lane', '12345' zip 
    union all 
    select '245 Meadowlane Dr', '12345' 
    union all 
    select '764 Pine Lane Ave', '12345' 
) 
select * from tbl 
where zip = '12345' 
    and (
      address ~* '^lane .*' 
     or address ~* '.* lane .*' 
     or address ~* '.* lane$' 
    ); 

address    zip 
-- 
South 23 where lane 12345 
764 Pine Lane Ave  12345 

那種正則表達式將不會返回「123大街」,如果你在WHERE子句中使用「23」,而不是「車道」。但它也不會讓你查詢楓樹街2300號的所有地址,公寓號碼和郵政信箱號碼也可以讓你大吃一驚。

+0

測試,我認爲這可能有效。而對於2300塊,我不希望在結果中有這種情況,但很高興知道。對於郵政信箱,我會在此之前進行額外的驗證 –

0

我想你可以嘗試這樣的:

SELECT * 
FROM tbl 
WHERE zip = 12345 
AND (address like '% ' + 'lane' + ' %' -- check in middle 
or address like 'lane' + ' %' -- check at beginning 
or address like '% ' + 'lane') -- check at end 

的Bt我建議反對。

如果你陷入困境的話,你可能會看到「全文搜索」功能更好,特別是因爲性能不會很好。

雖然我聽到新的Postgres支持。

+0

如果我這樣做,我也得到這個記錄,我不希望從第二組查詢。 123主要街道 –

+0

上面修正的小錯誤。因此,第二個查詢會變成類似於:地址(如'%23%')或地址(如'23%')或地址(如'%23')。這應該工作。它不? –