多对多标签条件选择

时间:2013-04-24 10:14:55

标签: mysql

我有三个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个(或更多)标记来获取文档。我们使用以下JOIN查询:

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'

在这种情况下,我们需要在条件中添加尽可能多的JOIN。所以他们的查询应该由一些脚本动态创建。是否有更优雅的方式来处理它?<​​/ p>

2 个答案:

答案 0 :(得分: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 :(得分: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