I was working with a simple mysql table in php when I came across this problem and I am wondering if there is a solution to this.
The table holds a username and his locations in a comma separated format.
id|user|locations
------------------
1 |abc | A, B, C
------------------
2 |xyz | P, Q, R
I was wondering if there was any way to write a mysql query so that it would return me a user who has location as A. Basically if one of the values among the comma separated values match, the record should be returned.
I know it is a better way to store them as separate records, but I was just curious if such a retrieval is possible. Thanks in advance.
Ideally, you should consider normalizing the data so you are not storing the comma separated list.
But if you cannot alter the table structure, MySQL has a FIND_IN_SET()
function that can be used to return the rows that match the value you want:
select id, user, locations
from yourtable
where find_in_set('A', locations)
We think
the following query may help you -
SELECT * FROM table
WHERE column
REGEXP '(^|,)A($|,)'
You can have a useful link in -
How to query comma delimited field of table to see if number is within the field
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.