V
V
Viktor Storozhenko2017-01-31 16:57:21
SQL
Viktor Storozhenko, 2017-01-31 16:57:21

Is it possible to make SQL of this kind?

Can you tell me if it is possible to make an SQL query capable of making the following selection:
there are 4 tables
1) Items
2) Tags
3) Categories
4) Items_Tags
of the relationship are as follows
Categories 1 - M Tags (Tags are divided into categories)
Items M - M Tags through the Items_Tags table
Example
Categories of tags Color, Length, Width
Tags (Red, Blue, Green), (Long, Short, Not long), (Wide, Narrow) respectively
Each Item can have any number of tags from any category, so a Item can be both Red and Green, Short and Long Items
are selected by tags as follows
Tags within the category Items are filtered by tags as follows
when selecting the tags Red, Blue, you need to find items that have either of these tags OR Red, OR Blue, OR both
tags Tags from different categories filter items in the following way
when choosing Red, Long, items that have BOTH these tags must be selected, while
the Item can have other tags, they are not relevant for the query.
Thus, in general, the rule can be written as follows
Select Items in which the selected tags are such that
category1 (tag1 OR tag2 OR tag3 ...) AND category 2 (tag4 OR tag5 ...) ...
Any number of tags in any number of categories can be selected, You need to show Items complying with the above rules
Is it possible to write such a request in principle? And if someone helps write, then there will be happiness!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2017-01-31
@Rsa97

SELECT `i`.`*`
  FROM `items` AS `i`
  JOIN `items_tags` AS `it` ON `it`.`item_id` = `i`.`id`
  JOIN `tags` AS `t1` ON `t1`.`id` = `it`.`item_id` 
    AND `t1`.`category_id` = 'Цвет'
    AND `t1`.`value` IN ('Синий', 'Красный')
  JOIN `tags` AS `t2` ON `t2`.`id` = `it`.`item_id` 
    AND `t2`.`category_id` = 'Длина'
    AND `t2`.`value` IN ('Длинный')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question