Filtro da join-table
Domanda
Ho dei problemi con una query SQL complicata.
Nel mio database MySQL ci sono le tabelle argomenti, tag e tags_topics per unirli. Voglio recuperare argomenti che condividono gli stessi tag specificati. Ad esempio, supponiamo di avere 3 tag con ID 1, 2 e 3, voglio recuperare tutti gli argomenti a cui sono associati i tag 1, 2 e 3. Gli argomenti possono avere altri tag, ma devono avere tutti i tag specificati.
Aiutami a pensare plz xD
EDIT: ho trovato una soluzione usando GROUP BY in questa domanda: Recupero solo delle righe che corrispondono a tutte le voci in una tabella unita (SQL) Se qualcuno ha una soluzione più elegante, si prega di pubblicare :)
Soluzione
ISCRIVITI
soluzione:
SELECT t.*
FROM topics t
JOIN tags_topics t1 ON (t.id = t1.topicId AND t1.tagId = 1)
JOIN tags_topics t2 ON (t.id = t2.topicId AND t2.tagId = 2)
JOIN tags_topics t3 ON (t.id = t3.topicId AND t3.tagId = 3)
Soluzione GROUP BY
:
Nota che devi elencare tutte le colonne t. *
nella clausola GROUP BY
, a meno che tu non usi MySQL o SQLite.
SELECT t.*
FROM topics t JOIN tags_topics tt
ON (t.id = tt.topicId AND tt.tagId IN (1,2,3))
GROUP BY t.id, ...
HAVING COUNT(*) = 3;
Soluzione di subquery:
SELECT t.*
FROM topics t
WHERE t.id = ANY (SELECT topicId FROM tags_topics tt WHERE tt.tagId = 1)
AND t.id = ANY (SELECT topicId FROM tags_topics tt WHERE tt.tagId = 2)
AND t.id = ANY (SELECT topicId FROM tags_topics tt WHERE tt.tagId = 3);
Soluzione GROUP BY
modificata:
Semplifica la clausola GROUP BY
isolando la ricerca in una sottoquery.
SELECT t.*
FROM topics t
WHERE t.id IN (
SELECT tt.topicId FROM tags_topics tt
WHERE tt.tagId IN (1,2,3))
GROUP BY tt.id HAVING COUNT(*) = 3
);
Altri suggerimenti
SELECT
topic_id
FROM
tags_topics
WHERE
tag_id IN (1,2,3)
GROUP BY
topic_id
HAVING
COUNT(*) > 2 /* or use COUNT(*) = 3 if you know that there cannot be duplicates in the junction table */