2012-06-14 24 views
1

说,有两个表。一个包含长文本值的字段(例如foobarbaz),另一个包含较短的值(foobarsomeothertext)。我想从两个表中检索具有以下条件的值:文本不能相等,但长字符串的开头必须与短字符串匹配。 Postgres有没有一种(整洁的)方式来做到这一点?提前致谢。比较PostgreSQL中的文本值

回答

1

如何:

SELECT <whatever> 
    FROM <your tables> 
WHERE one_field <> the_other_field 
    AND position(the_other_field in one_field) = 1; 

string functions and operators

+0

谢谢,这正是我需要的。 '1'是这里的第一个字符吗? –

+0

是的,1是第一场比赛的指数。如果不匹配,position()将返回0。 – dslh

+0

难道你不知道是否有办法用LIKE做到这一点?我不确定,因为我之前只看到过硬编码模式。 –

2

正如其他答案所说,“位置”可以使用...但我会使用正则表达式。

postgres=> create database test; 
CREATE DATABASE 
postgres=> \c test 
You are now connected to database "test". 
test=> create table long (long varchar); 
CREATE TABLE 
test=> create table short (short varchar); 
CREATE TABLE 
test=> insert into long values ('foobarbaz'); 
INSERT 0 1 
test=> insert into long values ('qfoobarbaz'); 
INSERT 0 1 
test=> insert into long values ('now this is a long text'); 
INSERT 0 1 
test=> insert into short values ('foobar'); 
INSERT 0 1 
test=> insert into short values ('someothertext'); 
INSERT 0 1 
test=> select long.long from long join short on long.long <> short.short and long.long ~ ('^' || short.short); 
    long  
----------- 
foobarbaz 
(1 row) 

警告,如果它包含正则表达式的东西,则可能必须转义为short。

(后编辑) - 这是它会怎样看使用LIKE(未测试)时,如:

select long.long 
from long 
join short on 
    long.long <> short.short and 
    long.long LIKE (short.short || '%'); 
+0

如果最初阅读这些选项,您是否认为其他答案代码的含义更明显? –

+0

如果您需要稍后扩展逻辑,则正则表达式具有优势。另外,如果长字符串很长,则第一个解决方案会出现性能问题,因为它必须通过完整的长字符串来搜索短字符串。 – tobixen

+0

开始思考,如果表格很大,你将会遇到两种解决方案的性能问题。这可能是你可以通过使用LIKE来利用索引,但我不能100%确定这一点。 – tobixen