D
D
dimk00z2020-05-15 12:02:44
SQL
dimk00z, 2020-05-15 12:02:44

SQL - complex many-to-many query?

Hello, I have not written requests for a long time, I need advice on the task:

The database contains a table with goods names(id INTEGER, name TEXT), a table with tags tags (id INTEGER, name TEXT) and a table linking goods and tags tags_names (tag_id INTEGER, goods_id INTEGER, UNIQUE (tag_id, goods_id)).
Print the id and names of all products that have all possible tags in this database.


I understand that it is necessary to display from the goods table, according to the condition, when the size of the tags table will match the number of records found for the id from tags_names.
The meaning is clear, but I will understand how to state it in a request

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mahmudchon, 2020-05-15
@mahmudchon

In fact, the task is the same as if we displayed all the products in the store, with the condition that the product can belong to several categories at once. Didn't check, but mb close.

SELECT `names`.`id`, `names`.`name` FROM `names` WHERE `names`
LEFT JOIN `tags_names` ON `names`.`id` = `tags_names`.`goods_id`
GROUP BY `names`.`id`

S
Sergey Pankov, 2020-05-15
@trapwalker

Something like this

SELECT n.id, n.name
FROM names n JOIN tags_names tn ON tn.goods_id = n.id
GROUP BY n.id, n.name
HAVING COUNT(DISTINCT tn.tag_id) = (SELECT COUNT(t.id) FROM tags t)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question