Farid Siddiqui
Farid Siddiqui

Reputation: 185

Like on a comma separated list in MySQL and PHP

I have a user_apps table.

enter image description here

One of the column is appid which is a search able. As you can I see the picture of the column I have made a mistake as I am storing a coma seprated list.

In the record 3,4 and 6 there are ids as "2," "2" and "12,"

if I do a like '%2%' i get all three records - which is wrong.

if i do a like '%2,%' i get 2, and 12, and miss 2 - again it is wrong.

is there anyway i can sort it out at code level

Upvotes: 0

Views: 114

Answers (2)

Marc B
Marc B

Reputation: 360922

Short term solution: find_in_set()

SELECT ... WHERE FIND_IN_SET('2', appid)

Long term + Real solution: Fix your database design and normalize it. Each of those separate numbers should be in its own record in a child table.

Hackish/even worse solution:

SELECT ... WHERE (appid = 2) OR (appid LIKE '%,2') OR (appid LIKE '2,%') OR (appid LIKE '%,2,%')

That covers all possible ways your value can show up in a CSV string: by itself, at the end of the string, at the start of the string, or somewhere in the middle.

Upvotes: 1

cyadvert
cyadvert

Reputation: 875

SELECT * FROM [tableName] WHERE FIND_IN_SET('2', appid)>0

Upvotes: 0

Related Questions