在PHP MySQL中从逗号分隔的字符串中查找确切的值 [英] Finding exact value from a comma separated string in PHP MySQL
本文介绍了在PHP MySQL中从逗号分隔的字符串中查找确切的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个产品表,其中包含一个名为类别"的字段,用于将与产品相关的类别ID保存为逗号分隔的值.我正在使用正则表达式从类别中搜索产品.
I have a product table which contains a field called 'categories' to save product related category ids as comma separated values. I am using regexp to search products from a category.
假定存在包含4,24,1,31
的记录
我的表情是,
Assume there is record containing 4,24,1,31
my expression is,
..WHERE categories REGEXP ',?4,?'
,但这将同时返回类别4
和24
but this returns both product of category 4
and 24
我只需要显示类别4
.
我想念什么吗?
推荐答案
使用
WHERE categories REGEXP "(^|,)4(,|$)"
如果用逗号括起来或在字符串的开头/结尾,则与4
匹配.
This matches 4
if surrounded by commas or at the start/end of the string.
在您当前的版本中,两个逗号都是完全可选的,因此24
中的4
匹配.
In your present version, both commas are entirely optional, so the 4
in 24
matches.
这篇关于在PHP MySQL中从逗号分隔的字符串中查找确切的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文