简体   繁体   中英

Finding exact value from a comma separated string in PHP MySQL

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.

Assume there is record containing 4,24,1,31 my expression is,

..WHERE categories REGEXP ',?4,?'

but this returns both product of category 4 and 24

I just need to display only category 4 .

Am I missing something?

Use

WHERE categories REGEXP "(^|,)4(,|$)"

This matches 4 if surrounded by commas or at the start/end of the string.

In your present version, both commas are entirely optional, so the 4 in 24 matches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM