3

在 PostgreSQL 我有一张桌子

tbl1
id -- RCODE -- COUNTRY --
1     US/MSR   United states of America
2     GY/LSR   Germany
3     CA/FSA   Canada

tbl2
id -- Name -- CCODE
33    T1      US        
44    Y1      CA       
55    W1      GY  

表可以在 tbl1 上的字段 RCODE 上与 tbl2 上的 CCODE 上的 LIKE 条件连接吗? 这样我得到的结果为

id --NAME-- RCODE -- CCODE--- COUNTRY

我将提供 tbl2 的 id 即)当我给 id 44 时,结果将是

id --NAME-- RCODE -- CCODE--- COUNTRY
44   Y1     CA/FSA   CA       Canada

谁能帮我解决这个查询,它是 PostgreSQL

一件事是RCODE中的前两个字符与表2中的CCODE相同。

4

2 回答 2

6
select tbl2.name, tbl1.rcode, tbl2.ccode, tbl1.country
from tbl1 
  join tbl2 on substring(tbl1.rcode, 1, 2) = tbl2.ccode
于 2012-09-17T12:37:11.190 回答
1

对于类似的问题,我使用了类似的东西:

select
tbl2.id as id,
tbl2.name as NAME,
tbl1.rcode as RCODE,
tbl1.ccode as CCODE,
tbl1.country as COUNTRY
from tbl1, tbl2
where substring(tbl1.rcode, 1, 2) = tbl2.ccode;

子字符串表达式中的数字是子字符串第一个字符的从 1 开始的索引,以及子字符串的长度。

其他字符串运算符,例如 trim()、lower() 和 upper() 也很有用。可用字符串运算符的更完整列表位于:

http://www.postgresql.org/docs/9.3/static/functions-string.html

于 2014-08-23T05:41:52.363 回答