views:

51

answers:

2

I have two tables

Table1: ColumnA (varchar)

Table2: ColumnB (varchar)

I need to get all rows from T2 where ColumnB is "like" any of the rows from 'ColumnA%'. For example, rows in T1 might be:

  • Summer09
  • Fall09

while rows in T2 might be

  • Spring09 Com101 Sec1
  • Summer09 Stat400 Sec2
  • Fall09 CS200 Sec3

In that scenario it would retun the Stat400 and CS200 rows. Is there a way to do this in a single SQL statement?

+3  A: 

SELECT T2.*
FROM T1, T2
WHERE T1.ColumnB LIKE T2.ColumnA + '%'

or


SELECT T2.*
FROM T1
INNER JOIN T2 ON T1.ColumnB LIKE T2.ColumnA + '%'

Probably not going to run very fast.

mgroves
You also might want to pad with spaces to account for one ColumnA value containing another ColumnA value. For example, if there were Fall09 and Fall091 the Fall09 would link to both sets in table 2. Probably not a problem in this situation since the number is zero-padded, but I've seen this problem before.
Tom H.
+1  A: 

this question points to a bad table design. my good friend Codd always said: do not combine multiple pieces of information into a single column!

t1 coulm should be split, so the semester and/or year should be their own column(s) with a FKs to the t2 table where the class info can be found using an index and no a slow LIKE!!

KM
I completely agree. Unfortunately it's a 3rd party app that we are adding functionality to. So re-engineering the DB isn't really an option
Jason
@Jason, I feel your pain!
KM