Answer the question
In order to leave comments, you need to log in
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.
Answer the question
In order to leave comments, you need to log in
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`
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 questionAsk a Question
731 491 924 answers to any question