Self Join?

From: bens_nospam(at)benjamindsmith(dot)com
To: <pgsql-sql(at)postgresql(dot)org>
Subject: Self Join?
Date: 2002-10-04 14:05:11
Message-ID: 200210042105.g94L5BL25197@chico.benjamindsmith.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

I'm having difficulty coming up with the right join to get my results.

I'm using PostgreSQL 7.2.x

I'm looking for a "most likely match" result. Assume you have a table with two fields, field 1 is a serial key (unique) and field 2 is varchar.

Assume that you have the following entries in the table:

recordid val
1, 'a'
2, 'b'
3, 'ab'

And I want to match the strings "a" and "b", but not necessarily "ab", and disregard an additional "c", and organize the result so that the records that best match are at the top. Sample output might be:

count recordid
2 3
1 1
1 2

Record #3, containing both "a" and "b" has two count, records 1 and 2 having only one of "a" or "b" have a count of 1.

The closest that I've come so far is from a query like

select id from table where lower(val) like lower('%a%') UNION ALL select id from table where lower(val) like lower('%b%') UNION ALL select id from table where lower(val) like lower(%c%');

What this gives me is
id
1
3
2
3

which is somewhat close, but then requires me to loop thru a potentially large number of results to get the requested output.

Anybody else up to this one?

-Ben

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 2002-10-04 14:14:06 Re: Can Postgres cache a table in memory?
Previous Message Richard Huxton 2002-10-04 13:37:54 Re: rows in order