Answer the question
In order to leave comments, you need to log in
Database architecture for filtering products - how to select by several properties at once?
Hello colleagues!
I'm trying to organize the storage of goods and their properties in MySQL. And at the same time be able to filter products by property values.
Created four tables
`article` - id, name
+----+------------------+
| id | name |
+----+------------------+
| 1 | T-shirt |
| 2 | T-shirt |
+----+------------------+
`prop` - id, name
+----+------------ --+
| id | name |
+----+------+
| 1 | Color |
| 2 | Size |
+----+--------------+
`prop_value` - id, name
+----+---------------- +
| id | value |
+----+----------------+
| 1 | White |
| 2 | Red |
| 3 | Big |
+----+----------------+
`prop2article` - id, article_id, prop_id, prop_value_id
+----+---------+ ---------------+------------+
| id | prop_id | prop_value_id | article_id |
+----+---------+---------------+------------+
| 1 | 1 | 1 | 1 |
| 2 | 1 | 2 | 1 |
| 3 | 2 | 3 | 1 |
+----+---------+---------------+------------+
Now I'm trying to select a product immediately by two properties - Color (1) = White (1) and Size (2) = Large (3):
SELECT DISTINCT article.name
FROM article
INNER JOIN prop2article ON article.id = prop2article.article_id
WHERE
(prop2article.prop_id = 1 and prop2article.prop_value_id = 1)
AND
(prop2article.prop_id = 2 and prop2article.prop_value_id = 3)
Answer the question
In order to leave comments, you need to log in
SELECT DISTINCT article.name
FROM article
INNER JOIN prop2article P1 ON article.id = P1.article_id
INNER JOIN prop2article P2 ON article.id = P2.article_id
WHERE
(P1.prop_id = 1 and P1.prop_value_id = 1)
AND
(P2.prop_id = 2 and P2.prop_value_id = 3)
Usage error in WHERE clause:
WHERE
(prop2article.prop_id = 1 and prop2article.prop_value_id = 1)
AND
(prop2article.prop_id = 2 and prop2article.prop_value_id = 3)
WHERE
(prop2article.prop_id = 1 and prop2article.prop_value_id = 1)
OR
(prop2article.prop_id = 2 and prop2article.prop_value_id = 3)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question