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 个(或更多)标签的文档。我们使用以下 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。所以他们的查询应该由一些脚本动态创建。有没有更优雅的方法来处理它?

4

2 回答 2

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
于 2013-04-24T10:20:35.323 回答
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')

在这里演示

于 2013-04-24T10:33:27.377 回答