2

I have a table table_a with a column containing data as follows:

.aaa01932
.asd02343
.lkj03342

So it always starts with a period followed by 3 letters, followed by 2 number (01, 02 etc) followed by some extra numbers.

I have another table table_b with data as follows:

aaa01
asd02
lkj03

So it maps to the data in table_a but with the period and the extra numbers at the end omitted.

How do I select from table_a joining on table_b where the data in the shown columns are "equal". By equal I mean that table_a.the_column like '%table_b.the_column%'. So something like:

Select * from table_a 
  join table_b on (table_a.the_column like '%table_b.the_column%');

Except I don't know how to format that like clause to accept a column inside. Maybe I need to concatenate it in somehow?

1
  • By using the '%' in the begining , you won't be able to use any index on this field, so not very efficient to join on this column. Commented Sep 23, 2010 at 13:59

3 Answers 3

10

The syntax for the LIKE would be:

table_a.the_column like '%' || table_b.the_column || '%'

An alternative would be SUBSTR:

table_b.the_column = substr(table_a.the_column,2,5)

As some comments have said, the SUBSTR is a better method for 2 reasons:

  • It can be indexed:

    create index on table_a (substr(the_column,2,5));

  • It is more accurate: you want to match only in that position, not anywhere in the column

Sign up to request clarification or add additional context in comments.

2 Comments

substr will be more suitable in this case (fixed lenght), we can use index at least.
SUBSTR would be better, assuming the pattern is fixed.
2

Try this:

Select * from table_a 
  join table_b on (table_a.the_column like '%' || table_b.the_column || '%');

Comments

1
join table_b on substr(table_a.column,1) = table_b.column

2 Comments

I believe this is a better option than LIKE, since we can use index in this case. Also to be more precise : substr(table_a.column,2,5)
I mean substr('.aaa01932',1) would produce 'aaa01932' and then we'll try to join on this condition 'aaa01932' = 'aaa01'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.