Mysql WHERE problem with comma-separated list

£可爱£侵袭症+ 提交于 2019-11-28 13:47:45

Short Term Solution

Use the FIND_IN_SET function:

SELECT uid 
  FROM tbl 
 WHERE FIND_IN_SET('401', artist_list) > 0

Long Term Solution

Normalize your data - this appears to be a many-to-many relationship already involving two tables. The comma separated list needs to be turned into a table of it's own:

ARTIST_LIST

  • artist_id (primary key, foreign key to ARTIST)
  • uid (primary key, foreign key to TBL)

Your database organization is a problem; you need to normalize it. Rather than having one row with a comma-separated list of values, you should do one value per row:

uid    artist
1      401
1       11
1        5
2        5
2        4
2        2

Then you can query:

SELECT uid
  FROM table
 WHERE artist = 401

You should also look into database normalization because what you have is just going to cause more and more problems in the future.

SELECT uid
FROM tbl
WHERE CONCAT(',', artist_list, ',') LIKE '%,401,%'

Although it would make more sense to normalise your data properly in the first place. Then your query would become trivial and have much better performance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!