How can i combine an IN and a LIKE statement in mysql query?

MySQL 5.5.54

I have two tables, both with the same structure.  I want to select records from table 1 based on the values in table 2.
I have a field, thevalue, which contains values such as:
181-1-0001
181-1-0002
181-2-0001
181-2-0004

I have the query:
SELECT * FROM table1 where thevalue  in(SELECT distinct concat('Like ''',left(rangeid,8),'%''') FROM table2)

when I run this query I don't get an error but 0 rows are returned.  when I run the inner select statement separately it returns

'Like \'181-1-00%\''
'Like \'182-1-00%\''
'Like \'183-2-00%\''
'Like \'187-2-00%\''
'Like \'188-2-00%\''

Can anyone suggest how I can return the rows in table1 where the first 8 characters of the thevalue field match those in the thevalue field of table2?
NemetonaAsked:
Who is Participating?
 
Pawan KumarDatabase ExpertCommented:
Please use like this ..

COL1 LIKE '%COL2%'

SELECT * FROM table1 a 
INNER JOIN table2 b ON LEFT(b.rangeid,8) LIKE CONCAT('%' , a.thevalue , '%' )

Open in new window

0
 
ste5anSenior DeveloperCommented:
Well, and consider normalization.. this kind of query will be a performance nightmare on large sets.
0
 
Julian HansenCommented:
It appears from your query you are trying to create a dynamic LIKE statement - you have shown us values from one table - what do the corresponding values from the other table look like - the same? If so why not do this

SELECT * FROM table1 WHERE thevalue in (SELECT DISTINCT rangeid FROM table2)

Open in new window


If not show us the other data so we can fix the query.
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
Pawan KumarDatabase ExpertCommented:
If thats what you need then do not use DISTINCT and IN clause. you can directly use this ..
DISTINCT is not required at all as we are just checking for existence of rows.

SELECT * FROM table1 a
WHERE EXISTS ( SELECT NULL FROM table2 b WHERE a.thevalue  = b.rangeid )

@Author - You just need to handle the where clause if you need any changes.
0
 
NemetonaAuthor Commented:
Thank you all.  While Pawan Kumar's solution did not quite work, as I needed to be able to edit the results, it gave me the idea on how to change my query to get what I needed.

SELECT * FROM table1 where left(thevalue,8) in(select left(thevalue,8) from table2)

Many thanks to you all.
0
 
NemetonaAuthor Commented:
Thank you
0
 
Pawan KumarDatabase ExpertCommented:
welcome glad to help as always :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.