2013-04-22 43 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