MySQL: Find if a value is in a list of values

Hi all,

I have a text field that contains a list of IDs e.g. 16,20,24,29,38,40

I need to find any records where that field contains a particular ID.

I thought that something like SELECT * FROM tablename WHERE IDlistfield CONTAINS myID but that doesn’t work.

Can anyone point me in the right direction?

TIA

Tom

What you should do is get rid of multiple values separated by commas in a column.

But something like this should work:

SELECT * 
FROM tablename 
WHERE IDlistfield LIKE '16%'
OR IDlistfield LIKE '%,16,%'
OR IDlistfield LIKR '%,16'

It would be better to change your data model to avoid putting comma separated values into a field. Searching will be easier. The code above is almost correct but if you have a number 16x then this will be accepted. Try this:


SELECT * 
FROM tablename 
WHERE IDlistfield = '16'
OR IDlistfield LIKE '16,%'
OR IDlistfield LIKE '%,16,%'
OR IDlistfield LIKR '%,16'

Ah yes, I forgot the , after the 16. And I forgot the 16 as a single value too. Good catch!

WHERE FIND_IN_SET(‘16’,IDlistfield) > 0

but all of these solutions are slow, and will not scale – the more rows in the table, the slower the query gets

you should normalize that data

Thanks to everyone for your replies. I wish I could rearrange the data but I’m stuck with it.

I’ll check out your book Rudy.

Cheers