1

I am developing php script with MySQL . I stored genre datas as "1, 2 ,3"(IDs)

Then I have a problem with searching data.

My Data table is:

metas table

-------------------
meta_id,meta_genres
--------------------
|1     |1,2,3      |

|2     |10,3,4     |

|3     |12,3,5     |

-------------------

my query is

SELECT * FROM metas WHERE meta_genres LIKE '%1%'

then return ids: 1,2,3

I want to it returns just 1.

How can I fix it ?

Best Regards.

7
  • 3
    @Gowri : nope...this would fail if 1 is in last..like 4,3,1! Commented Oct 6, 2014 at 9:33
  • You question isn't that precise, so I'll assume that you want to get the ID (tell me if I guess wrong) of the meta_genre which fit your need. So you should just change the SQL query in SELECT meta_id FROM metas WHERE meta_genre LIKE '%1%'; Commented Oct 6, 2014 at 9:33
  • 1
    If you can't normalize your tables properly, use FIND_IN_SET() but you should really normalize for better efficiency Commented Oct 6, 2014 at 9:33
  • I would advise you to bring your database up to the 3rd normalize form! ->en.wikipedia.org/wiki/Database_normalization Commented Oct 6, 2014 at 9:34
  • SELECT * FROM metas WHERE meta_genres LIKE '%1,% OR meta_genres like '%,1% should do the trick Commented Oct 6, 2014 at 9:35

3 Answers 3

4

Use FIND_IN_SET(str,strlist) function:

SELECT *
 FROM metas
 WHERE FIND_IN_SET(1, meta_genres)

EDIT: if there are spaces before commas (e.g. 1 , 2 , 3) in meta_genres then above query can return empty set. To work around:

SELECT *
 FROM metas
 WHERE FIND_IN_SET(1, REPLACE(meta_genres, ' ', ''));
Sign up to request clarification or add additional context in comments.

1 Comment

Dear Rimas, Your answer seems to be good. However it returns nothing. My query is true but I don't understand
1

You can also use REGEXP to find only separated 1 in set input

SELECT * FROM metas WHERE meta_genres REGEXP '[[:<:]]1[[:>:]]'

Comments

-1

You Will never retrive just 1, thats because the numbers after 1 is part of 2,3 string. So the query does not look at these numbers as individual numbers but simply as a whole string.....

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.