2011-01-11 7 views
1

Ich habe eine Datenbank, die Inhalt nach Taxonomie bezieht, und ich versuche, diesen Inhalt nach Taxonomie abzufragen. Es sieht wie folgt aus:SQL-Taxonomie-Hilfe

Table 1 

content_id, content_name 

Table 2 

content_id, content_taxonmoy 

Was ich in meiner Anfrage versuche mit zwei oder mehr Arten von nahe stehenden Taxonomie Inhalt zu finden ist. Meine Abfrage sieht so aus:

SELECT content_id FROM table_1 JOIN table_2 ON table_1.content_id=table_2.content_id WHERE content_taxonomy='ABC' AND content_taxonomy='123' 

Außer es gibt nichts zurück. Ich versuchte später eine Gruppe mit:

SELECT content_id FROM table_1 JOIN table_2 ON table_1.content_id=table_2.content_id WHERE content_taxonomy='ABC' AND content_taxonomy='123'GROUP BY content_id, content_taxonomy 

Aber das hat auch nicht funktioniert. Irgendwelche Vorschläge bitte?

Antwort

1
SELECT * 
FROM content c 
WHERE (
     SELECT COUNT(*) 
     FROM taxonomy t 
     WHERE t.content_id = c.content_id 
       AND t.content_taxonomy IN ('ABC', '123') 
     ) = 2 

erstellen UNIQUE INDEX oder ein PRIMARY KEY auf taxonomy (content_id, content_taxonomy) für diese schnell zu arbeiten.

SELECT c.* 
FROM (
     SELECT content_id 
     FROM taxonomy 
     WHERE content_taxonomy IN ('ABC', '123') 
     GROUP BY 
       content_id 
     HAVING COUNT(*) = 2 
     ) t 
JOIN content c 
ON  c.content_id = t.content_id 

In diesem Fall erstellen UNIQUE INDEX oder ein PRIMARY KEY auf taxonomy (content_taxonomy, content_id) (die Reihenfolge oder die Felder beachten).

Jede Lösung kann mehr oder weniger effektiv sein als eine andere, abhängig davon, wie viele Taxonomien pro Inhalt Sie haben und wie hoch die Wahrscheinlichkeit ist, dass eine Übereinstimmung gefunden wird.