0

I have a table of blog and there is filed of category,Varchar.I store there values with a comma to separate them like 5,6,9.

When I search with IN operator it not show result like

Table data in POST

Id     post_title      category      status
1      Title 1         5,4,9           1
2      Title 2         6               1
3      Title 3         6,9             1
4      Title 4         5,4,8           1
5      Title 5         6,7             1
6      Title 6         1,2,3           1
7      Title 7         4,9,8           1
8      Title 8         5,4,9           1

I try both queries below

SELECT * FROM POST WHERE category IN('6', '9');
SELECT * FROM POST WHERE category IN(6, 9);

Expected result would be

Id     post_title      category      status
1      Title 1         5,4,9           1
2      Title 2         6               1
3      Title 3         6,9             1
4      Title 5         6,7             1
5      Title 7         4,9,8           1
6      Title 8         5,4,9           1

I want to create a query to show related post of particular post category ids. If I open post and that is in multiple category. Then I want to show related post from multiples categories.

Thanks looking for best result.

If possible provide a query in PDO also

Hiiro
  • 55
  • 10
  • 2
    Duplicate of https://stackoverflow.com/questions/28639692/query-with-multiple-values-in-a-column/28639762#28639762 – Barmar Apr 21 '18 at 15:30
  • 3
    Fix your data model. You should have another table called `PostCategories` with one row per post and one per category. Your method of representing data is simply wrong for a relational database. – Gordon Linoff Apr 21 '18 at 15:30
  • 1
    https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad – chris85 Apr 21 '18 at 15:33
  • Possible duplicate of [SQL SELECT WHERE field contains words](https://stackoverflow.com/questions/14290857/sql-select-where-field-contains-words) – Alexander Apr 21 '18 at 15:33
  • 2
    @Alexander I wouldn't use that answer. The data is delimited so that will find false matches e.g. `like '%1%'` would bring back `1` but also `11`, `100`, etc. – chris85 Apr 21 '18 at 15:42
  • 1
    You could search for `like '%,1,%'`, being sure to concatenate a comma onto the front and back of the column, but fixing the data model is a better choice. – Greg Schmidt Apr 21 '18 at 16:16
  • Possible duplicate of [Query with multiple values in a column](https://stackoverflow.com/questions/28639692/query-with-multiple-values-in-a-column) – Paul Spiegel Apr 21 '18 at 18:00

0 Answers0