Reputation: 53
I have a table where the table has a category field is array value LIKE :
|-----------------------------------|
|post_id | name | category_id |
-------------------------------------
|1 | test1 | 1,2,45 |
|2 | test2 | 2,7 |
|3 | test3 | 7,13,56 |
|-----------------------------------|
From drop down select box if i select CATEGORY ID 2. i should get the result of TWO ROWS. because post_id 1 and 2 have 2 in category_id. i don't know how to do query for it. i struggled a lot. please help me out. Thanks in advance.
Upvotes: 0
Views: 849
Reputation: 13128
There is a simple way to sort this out.
You can change the datatype of category_id
to SET
and using something like this:
SELECT * FROM table WHERE FIND_IN_SET('2', category_id);
Read more: FIND_IN_SET
Also look at flauntster' answer for the most appropriate way to do it.
Upvotes: 3
Reputation: 2016
If posts can be in multiple categories, then you should reconsider the use of arrays in the category_id field, and instead use a post/category reference table, with a structure such as:
id postId catId
This way, you can get all posts in category 2 by (lets call this reference table 'PostCats'):
SELECT postId FROM PostCats WHERE catId=2
Upvotes: 6