E
E
Evgeniy Odinets2015-06-01 20:45:48
PHP
Evgeniy Odinets, 2015-06-01 20:45:48

How to implement multiple categories for an article?

Good day.
In the database I have a table where posts for the site are stored, which have several categories:
+---+----------+
| id | cat_id |
+---+----------+
| 1 | 1, 5, 11 |
+---+----------+
And the table of the categories themselves:
+---+---------+
| id | name |
+---+--------+
| 1 | cat1 |
+---+--------+
How to do select count() to count how many posts have category 1?

$cat_id = '1';

SELECT count(id) FROM `posts` WHERE cat_id LIKE '%$cat_id%';

For category 1, it counts all categories that have 1 in id: 1, 11, 12, 13, etc.
How to make a correct count that would only count the integer value 1, not 11

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Lebedev, 2015-06-01
@evgeniy2194

It will work terribly slowly.
Make a separate table:
+---+----------+
| id | cat_id |
+---+----------+
| 1 | 1 |
+---+----------+
| 1 | 2 |
+---+----------+
| 2 | 3 |
+---+----------+

E
Eugene, 2015-06-01
@ElForastero

Enumerations in tables - not to eat buzzing. Does not correspond to the first normal form with its atomicity.
They are always advised to leave them in the direction of other solutions. Alexei Lebedev speaks his mind.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question