mysql - How to select number with LIKE? -
I have a bunch of products, and there is a bunch of category pages. One product can be in many categories, so in my database, I have a product table with the "Categories" column. In this column, I store the ID of all the categories that are stored in the current product, separated by a semicolon it occurs.
Example: 1; 5; 23; 35; 49;
.
When I browse Category Category ID 5, I want to see all the products that have the code 5;
I currently do this
from SELECT * where categories like "%" category ";%"
The problem is that it matches more than just 5. This is 15;
or 25; Matches
.
Then the question:
- How can I make sure that I will choose only the number that I want? If the range is "5", then I do not want to match it in 15, 25, 35 and so on.
- Perhaps it is a very bad way to store category-ids, are there any suggestions for a different way of storing products related to that category? P> Answer to two questions / comments:
-
The only way I can think you can do it without modifying your schema (see # 2) is a MySQL regular expression But this is not really a good idea though look for the document
-
You are right - this is not a good way to store categories. What you want is also known as a junction table (see). There are three tables in a way:
product
,category
, and aproduct_categories
table. You will have a unique ID already in the product and category, and the product cabage table will have two columns: product_id and category_id. If the product falls under 1 categories 10 and 11, then you will have two lines in the ProductCages table: 1,10 and 1,11
-
If you need more then I can extend help, but it should start repartitioning your database (more) correctly.
Comments
Post a Comment