I know that I can use IN(1,2,3) to select items from an SQL database where their value is either 1, 2 or 3, but what if I have a value in MYSQL which is a string, and is equal to ‘1,2,3’ and I want to select that value. As far as I know I have to do this:
SELECT whatever FROM wherever WHERE sqlvariable = '1' OR sqlvariable LIKE '1,%' OR `sqlvariable` LIKE '%,1,%' OR `sqlvariable` LIKE '%,1'
which is fine if I want to simulate ‘IN’ sort of in reverse. But lets say I want to select sqlvariable where it contains either 1 or 2, then I have to do this:
SELECT whatever FROM wherever WHERE sqlvariable = '1' OR sqlvariable LIKE '1,%' OR `sqlvariable` LIKE '%,1,%' OR `sqlvariable` LIKE '%,1' OR sqlvariable = '2' OR sqlvariable LIKE '2,%' OR `sqlvariable` LIKE '%,2,%' OR `sqlvariable` LIKE '%,2'
Now lets say I use PHP to generate the above queries and I’m looking to find sqlvariable where it contains a 1 2 4 66 34 33 22 44 or 992. It’s going to take an awfully long time for this query to run.
I could do a bitwise implementation, but then I’m limited to only having about 60 different items or so which isn’t enough.
Is there a faster way to utilize a CSV query like the above in sql? I suppose it’s sort of like IN() but in reverse.
You can simplify your queries using
FIND_IN_SET:This however will still require searching every row in the table. It would be better to redesign your database so that CSV formatted data is not required.
Update: Your existing design looks something like this:
You should change it to something more like this: