2013-04-24 92 views
2

我有三個MySQL表格 - 文檔,文檔標籤和多對多關係表(帶有文檔ID和標籤ID)。多對多標籤有條件選擇

Document 
+------+ 
| id | 
+------+ 
| 1 | 
| 2 | 
| 3 | 
| 4 | 
+------+ 

DocumentToTag 
+------+------+ 
|idDoc |idTag | 
+------+------+ 
| 1 | 1 | 
| 1 | 2 | 
| 2 | 1 | 
| 2 | 3 | 
| 4 | 4 | 
+------+------+ 

Tag 
+------+-------+ 
| id | value | 
+------+-------+ 
| 1 |  2 | 
| 2 |  4 | 
| 3 |  8 | 
| 4 | 42 | 
+------+-------+ 

有必要使用具有特定值的2(或更多)標籤獲取文檔。我們用下面的連接查詢:

SELECT DISTINCTROW 
Document.id 

FROM Document 
LEFT JOIN DocumentToTag AS dt1 ON dt1.idDoc = Document.id 
LEFT JOIN Tag AS tag1 ON dt1.idTag = tag1.id 
LEFT JOIN DocumentToTag AS dt2 ON dt2.idDoc = Document.id 
LEFT JOIN Tag AS tag2 ON dt2.idTag = tag2.id 

WHERE tag1.value = 'someTagValue' 
AND tag2.value = 'someOtherTagValue' 

在這種情況下,我們需要做的很多連接,我們需要在條件添加儘可能多的標籤。所以他們的查詢應該由一些腳本動態地創建。有沒有更優雅的方式來處理它?

回答

4

試試這個:

SELECT 
Document.id 
FROM Document 
    JOIN DocumentToTag AS dt1 
     ON dt1.idDoc = Document.id 
    JOIN Tag AS t 
     ON dt1.idTag = t.id 
WHERE t.value IN ('tag1', 'tag2', 'tag3') -- you can dynamicaly generate this list 
GROUP BY Document.id 
HAVING COUNT(DISTINCT t.value) = 3 -- you can pass this as parameter 
+1

+1外部聯接的有效轉變成一個內由where子句加入。 – 2013-04-24 10:29:53

+0

@MarkBannister是的,當然,它只是複製/粘貼:) – 2013-04-24 10:31:04

+0

@HamletHakobyan非常感謝您的快速響應! – zavg 2013-04-24 10:41:02

0

你可以看這個

SELECT DISTINCT 
    Document.id 
    FROM Document 
LEFT JOIN DocumentToTag AS dt1 ON dt1.idDoc = Document.id 
LEFT JOIN Tag AS tag1 ON dt1.idTag = tag1.id 

WHERE tag1.value in ('someTagValue' ,'someOtherTagValue') 

DEMO HERE