Query related data based on “like” statement
-
16-09-2019 - |
Question
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?
Solution
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.
OTHER TIPS
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!!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow