2013-04-22 42 views
0

我試圖做一個左連接上兩個表hstore列:postgres左加入在hstore上使用正則表達式?

SELECT 
    d.context->'hostname' AS hostname, 
    r.data->'Site' AS site, 
    r.data->'Region' AS rack, 
    r.data->'Manufacturer' AS vendor, 
    r.data->'ModelNumber' AS model_number, 
    FROM dns AS d 
    LEFT JOIN rack AS r ON 
     d.context->'hostname' ~ r.context->'Name' 
    ; 

其中兩個dnsrack有兩個hstore列contextdata;左連接的條件是rack.context->'Name'可能只包含fqdn'd dns.context->'hostname'的一部分。

然而,當我嘗試了上面,我得到

ERROR: operator does not exist: text ~ hstore 

什麼想法?

+0

什麼postgres版本?可能是運營商的優先事項?你有沒有嘗試在兩個hstore查找周圍放置圓括號以確保它們都是字符串(如果這是你想要的) – 2013-04-22 17:40:29

回答

2

你有一個優先問題。這:

d.context->'hostname' ~ r.context->'Name' 

被解析如下:

d.context -> ('hostname' ~ r.context) -> 'Name' 

所以~正試圖以配合r.context HSTORE的'hostname'文本值。添加一些小括號強制問題:

(d.context->'hostname') ~ (r.context->'Name') 

如果我們看看operator precedence table,你會看到這一點:

  • stuff that doesn't contain ~ or ->
  • (any other) : all other native and user-defined operators
  • more stuff that doesn't contain ~ or ->

因此,無論~->落入「其他」類別。我猜~被添加到->之前的運營商列表中,因爲~是本地運營商,而->是由hstore擴展添加的。


有趣的是,更多的東西,不包含~->列表確實包含LIKE和這樣的:

hstore1 -> k1 like hstore2 -> k2 

作品在這裏預期的那麼:

select 'a=>b'::hstore -> 'a' like 'a=>b'::hstore -> 'a'; 
select 'a=>b'::hstore -> 'a' ~ 'a=>b'::hstore -> 'a'; 

第一個查詢將會是't'而第二個會產生你的「操作符不存在」的錯誤。我只提到這一點,因爲我預計LIKE,SIMILAR~運營商具有相同的優先順序,因爲它們都是同一主題上的所有變體。

+0

感謝你的迴應:所以你是正確的,使用'LIKE'按預期工作,但是,我仍然無法獲得要操作'〜'運算符。當我使用'(d.context - >'hostname')〜(r.context - >'Name')'時,它返回'ERROR:無效正則表達式:量詞操作數無效' – yee379 2013-04-22 21:21:53

+0

@ yee379:什麼是'r .context - >'名稱'在這些情況下看起來像?而正則表達式可能根本就不是正確的解決方案,如果你只想'r.context - >'Name''在'd.context - >'hostname''的末尾,那麼['position']( http://www.postgresql.org/docs/current/interactive/functions-string.html#FUNCTIONS-STRING-SQL)字符串函數可能比正則表達式更好。 – 2013-04-22 21:31:20

+0

'r。上下文 - >'名稱'通常是一個非fqdn'd主機名,所以是的,使用'LIKE(r.context - >'Name'||'%')可以工作,因爲它只是比較一個fdqn'd主機名(不太確定的位置會非常適合這裏)。然而,我只是困惑,爲什麼'〜'仍然不起作用 - 即使它們被包裹在圓括號中。乾杯! – yee379 2013-04-22 21:48:55