简体   繁体   中英

Like on a comma separated list in MySQL and PHP

I have a user_apps table.

在此处输入图片说明

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

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.

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

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