0

I Made two tables

  1. posts
  2. categories

In posts table I created category column, here I store multiple category_id like this 1,2,3.

The problem is if category column has single category_id like 1 or 2 or 3, I can easily query the data like this:

SELECT title FROM posts WHERE category = $category_id

However, I am unsure as to how to query the comma-delimited data. Is there a way to do this, or should I change the table structure ?

4
  • Add another table. Call it posts_categories with post_id and category_id. Commented Nov 10, 2016 at 13:38
  • Never, ever store data as comma separated items. It will only cause you lots of trouble. Commented Nov 10, 2016 at 13:39
  • Add a junction table which has 2 foreign keys refering to both Posts table and Categories table. like @aynber said. the 3th table will only refere foreign keys to the primary tables. Commented Nov 10, 2016 at 13:40
  • Why the MS SQL Server tag? Commented Nov 10, 2016 at 13:42

2 Answers 2

1

enter image description here

Here you can have: Categoryid: 1 Postid: 1,2,3

Result = Categoryid: 1 --> Postid 1,2,3

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

Comments

0

You could either create a junction table (probably with an EAV design) or keep your unique table and use FIND_IN_SET, as such :

SELECT title FROM posts WHERE FIND_IN_SET(1, category) > 0

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.