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?
MySQL has an inbuilt function called FIND_IN_SET which will search for values within a comma separated values. It basically returns the index position of the first parameter within the second parameter. This can be alternatively used to replace the IN clause. WHERE FIND_IN_SET (item_description,'Mobile,laptop');
In MySQL, you can return your query results as a comma separated list by using the GROUP_CONCAT() function. The GROUP_CONCAT() function was built specifically for the purpose of concatenating a query's result set into a list separated by either a comma, or a delimiter of your choice.
The task is to split the given string with comma delimiter and store the result in an array. Use explode() or preg_split() function to split the string in php with given delimiter. PHP | explode() Function: The explode() function is an inbuilt function in PHP which is used to split a string in different strings.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With