Domanda

Ho bisogno di una query sql che recupererà tutti gli elementi che hanno entrambi i tag, non nessuno dei tag. Ho già una query, ma restituisce tutti gli elementi che hanno entrambi i tag, risultato non previsto. Trova la descrizione dettagliata di seguito. Grazie!

Struttura della tabella:

ITEMS TABLE
------------
item_id
item_name

TAGS TABLE
----------
tag_id
tag_name

ITEMTAGS TABLE
---------------
tag_id
item_id

Domanda:

SELECT Items.* FROM Items 
INNER JOIN ItemTags ON Items.item_id = ItemTags.item_id
WHERE ItemTags.tag_id IN (T1, T2)
GROUP BY Items.item_id

Risultato: Tutti gli articoli che hanno T1 o T2

Risultato atteso: Tutti gli articoli che hanno sia T1 che T2

È stato utile?

Soluzione

select i.*
from items i, itemtags it1, itemtags it2
where i.item_id=it1.item_id and it1.tag_id=T1
and i.item_id=it2.item_id and it2.tag_id=T2;

Altri suggerimenti

Se il tuo database supporta la parola chiave intersect (lo fa SqlServer) puoi scrivere:

SELECT Items.* 
FROM Items 
WHERE Items.item_id in 
/* intersection between items that have the tag T1 
   and the ones that have the tag T2 */ 
(
    SELECT item_id FROM ItemTags WHERE tag_id = T1
    INTERSECT 
    SELECT item_id FROM ItemTags WHERE tag_id = T2
)

In caso contrario, dovrai fare qualcosa del tipo:

SELECT Items.* 
FROM Items 
WHERE Items.item_id in 
(
    SELECT ItemTags1.item_id 
    FROM ItemTags as ItemTags1 
        INNER JOIN ItemTags as ItemTags2 
        ON ItemTags1.item_id = ItemTags2.item_id 
    WHERE 
            ItemTags1.tag_id = T1
        AND ItemTags2.tag_id = T2
)

Nella seconda query prendersi cura di possibili problemi di prestazioni a causa di ItemTags1.item_id = ItemTags2.item_id. Avrai bisogno di un indice sulla chiave esterna per funzionare bene.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top