I have a column in one of my table where I store multiple ids seperated by comma’s.
Is there a way in which I can use this column’s value in the “IN” clause of a query.
The column(city) has values like 6,7,8,16,21,2
I need to use as
select * from table where e_ID in (Select city from locations where e_Id=?)
I am satisfied with Crozin’s answer, but I am open to suggestions, views and options.
Feel free to share your views.
Building on the FIND_IN_SET() example from @Jeremy Smith, you can do it with a join so you don’t have to run a subquery.
This is known to perform very poorly, since it has to do table-scans, evaluating the FIND_IN_SET() function for every combination of rows in
tableandlocations. It cannot make use of an index, and there’s no way to improve it.I know you said you are trying to make the best of a bad database design, but you must understand just how drastically bad this is.
Explanation: Suppose I were to ask you to look up everyone in a telephone book whose first, middle, or last initial is “J.” There’s no way the sorted order of the book helps in this case, since you have to scan every single page anyway.
The
LIKEsolution given by @fthiella has a similar problem with regards to performance. It cannot be indexed.Also see my answer to Is storing a delimited list in a database column really that bad? for other pitfalls of this way of storing denormalized data.
If you can create a supplementary table to store an index, you can map the locations to each entry in the city list:
Assuming you have a lookup table for all possible cities (not just those mentioned in the
table) you can bear the inefficiency one time to produce the mapping:Now you can run a much more efficient query to find entries in your
table:This can make use of an index. Now you just need to take care that any INSERT/UPDATE/DELETE of rows in
locationsalso inserts the corresponding mapping rows inlocation2city.