Domanda

Data una tabella di elementi, una tabella di tag e una tabella di join tra loro, qual è un modo buono ed efficiente per implementare le query del modulo:

p1 AND p2 AND ... AND pn AND NOT n1 AND NOT n2 ... AND NOT nk

Sto usando SQL. Quindi, per trovare tutti gli elementi che corrispondono a tutti i tag p1 ... pn e nessuno di n1 ... nk?

Esiste un buon "standard"? soluzione per questo?

È stato utile?

Soluzione

Difficile dirlo senza conoscere il tuo schema, ma qualcosa del genere funzionerebbe:

select article_id from articles
inner join tag t1 on t1.article_id=articles.article_id and t1.tag='included_tag'
inner join tag t2 on t2.article_id=articles.article_id and t2.tag='another_included_tag'
left outer join tag t3 on t3.article_id=articles.article_id and t3.tag='dont_include_tag'
left outer join tag t4 on t4.article_id=articles.article_id and t4.tag='also_dont_include_tag'
where t3.tag_id is null and t4.tag_id is null

join interno ai tag che devono essere inclusi ed eseguono un anti-join (join esterno + dove una colonna richiesta è nulla) ai tag che non devono essere inclusi

Altri suggerimenti

Penso che questo sia quello che stai cercando:

SELECT * FROM TABLE_NAME WHERE COLUMN1 IN ('value1','value2','value3') AND COLUMN1 NOT IN ('value4','value5','value6')

In caso contrario, fammi sapere. Potrei aver frainteso la tua domanda.

Dipende da come si stanno archiviando i tag nel database, ma probabilmente si desidera l'operatore IN :

SELECT tag FROM myTags WHERE tag IN ('p1','p2',...)
SELECT tag FROM myTags WHERE tag NOT IN ('p1','p2',...)
SELECT DISTINCT itemID FROM ItemsTags it, Tags t 
WHERE it.tagID = t.ID AND t.tag IN ('p1','p2','p3') AND t.tag NOT IN ('p4','p5','p6')
SELECT i.title
  FROM items i
 WHERE EXISTS(SELECT * FROM join_table j JOIN tags t ON t.id = j.tag_id WHERE j.item_id = i.id AND t.name = 'tag1')
   AND NOT EXISTS(SELECT * FROM join_table j JOIN tags t ON t.id = j.tag_id WHERE j.item_id = i.id AND t.name = 'tag2')

Il server SQL fa un buon lavoro su questo costrutto, ma Oracle potrebbe aver bisogno di qualche suggerimento per farlo bene (almeno 5 anni fa).

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