0

Data stored in the database as below where category is column name and comma separated strings are values.

category = 'cat,cat1,cat2,cat3,cat33,cat4';

I'm trying to search with a category from the list:

$query= mysqli_query($mysqli, "SELECT * FROM table where
INSTR(category,'cat3') > 1 ");

But this doesn't work because the result includes cat3 and cat33.

Any thoughts on how I can do this search, please?

Thanks!

3
  • 4
    "Data stored in the database as below where category is column name and comma separated strings are values"—this is a sure sign that you've got a data modeling problem. Multiple values shouldn't be crammed into a single field in your database. Commented Jul 23, 2018 at 22:04
  • 2
    Someone may suggest using FIND_IN_SET, but the best answer is normalization. Commented Jul 23, 2018 at 22:08
  • If you don't yet have the select working for this, I'm gonna presume that means it's not live, otherwise it wouldn't be doing anything. Honestly, extending the comments above, you should take this time while it's not live to add a new table called (eg) categories and have each category as a separate row with data in other columns relevant to each cat Commented Jul 23, 2018 at 22:25

3 Answers 3

3

You can use FIND_IN_SET function :

SELECT * FROM table where FIND_IN_SET('cat3', category) > 0

But you should normalize your data by creating category table and relate to your table's primary key

Sign up to request clarification or add additional context in comments.

Comments

0
"SELECT * FROM table where category LIKE '%cat3,%'";
"SELECT * FROM table where category LIKE '%cat33,%'";

if you don't want to add comma to the end of each category name, then "SELECT * FROM table where category LIKE '%cat3,%' OR category LIKE '%cat3'";

3 Comments

This will miss the last value in the list.
"SELECT * FROM table where category LIKE '%cat3,%' OR category LIKE '%cat3'";
This will also match a category called "somecat3". If you're going to do it the wrong way and not normalize your tables, you could instead use a regular expression: SELECT * FROM table where category REGEXP '(^|,)cat3(,|$)'.
0

You can "solve" this using the query below. BUT I HARDLY RECCOMEND you to normalize your database and use this only if you REALLY NEED

SELECT * FROM table WHERE fild LIKE '%,camp3,%' OR fild LIKE 'camp3' OR field LIKE '%,camp3'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.