MySQL search for 1,2,3,11,22,33 in field

荒凉一梦 提交于 2020-01-05 09:21:28

问题


Can I search for 1 AND 2 AND 3 without getting a false match because 11,22,33 are in the field?

A field that has the string = "11,22,33" should then not return any results.


回答1:


First of all, using comma separated values in a field is problematic, and you should consider storing them in a sepatate table instead. Then you could get the record more efficiently:

select ...
from mainTable t
inner join valueTable v1 on v1.id = t.id and v1.value = 1
inner join valueTable v2 on v2.id = t.id and v2.value = 2
inner join valueTable v3 on v3.id = t.id and v3.value = 3

If that is not possible, you have to go the slow string matching way. To match the values in a comma separated string, you can use the like operator:

... where
  concat(',', someField, ',') like '%,1,%' and
  concat(',', someField, ',') like '%,2,%' and
  concat(',', someField, ',') like '%,3,%'

Putting the separator on both sides of the searched value makes sure that you don't get any false positives. Adding the commas before and after the field value makes sure that you can find the first and last value.




回答2:


Use regular expression matching with the regexes (^|,)1($|,) and (^|,)2($|,) and (^|,)3($|,)




回答3:


Have you considered what an optimal search for the value 11 would do in your case?

Since there's no way to narrow down the search, it is doomed to perform a table-scan to find the relevant values.

You should seriously consider splitting those values up into a separate table, where you have one row per value, all linked back to the original row in the original table.

This would be far more correct, far more performant, and far easier to deal with.

Having said that, if you still want to use your current approach, you can search for a value by doing this:

WHERE ','+ column + ',' LIKE '%,' + value + ',%'

This will search ',11,22,33,' for '%,11,%', note the commas at each end of both the column and the value, this will ensure you don't get false positives due to partial matches.




回答4:


http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set

FIND_IN_SET(1,column) AND FIND_IN_SET(3,column) AND etc;

Its designed to be used with the SET type, but it also works with a basic comma seperated list.



来源:https://stackoverflow.com/questions/2022872/mysql-search-for-1-2-3-11-22-33-in-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!