Link to home
Create AccountLog in
Avatar of Nemetona
Nemetona

asked on

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?
ASKER CERTIFIED SOLUTION
Avatar of Pawan Kumar
Pawan Kumar
Flag of India image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of ste5an
Well, and consider normalization.. this kind of query will be a performance nightmare on large sets.
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.
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.
Avatar of Nemetona
Nemetona

ASKER

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.
Thank you
welcome glad to help as always :)