如何选择与所有必需标签匹配的帖子?

时间:2012-01-06 15:57:24

标签: mysql

我有一个包含两列的表,博客帖子ID和标签ID。一篇博文可以有几个标签,比如它是关于“纽约”和“Soho”的帖子。假设我想找到所有标记为1和2的博客文章,我该怎么做?

blogPostToTags
=============================
id           |tagId
-----------------------------
1            |1
1            |2
2            |1
3            |2

更新:

我尝试了以下内容:

SELECT id FROM blogPostToTags WHERE tagId = 1 AND tagId = 2

SELECT id FROM blogPostToTags WHERE tagId = 1 OR tagId = 2

既不工作......

3 个答案:

答案 0 :(得分:2)

使用双JOIN

SELECT id
FROM blogPosts p
INNER JOIN blogPostToTags pt1 ON pt1.id = p.id
INNER JOIN blogPostToTags pt2 ON pt2.id = p.id
WHERE pt1.tagId = 1 AND pt2.tagId = 2;

答案 1 :(得分:0)

SELECT `id`, COUNT(*) FROM
    (SELECT `id` FROM `blogPostToTags` WHERE `tagId` = 1)
    UNION
    (SELECT `id` FROM `blogPostToTags` WHERE `tagId` = 2)
    AS `_`
    -- this temporary table contains an entry for each `id` when
    -- the tag ID matches. I assume that `id`,`tagId` is a UNIQUE key.
    -- COUNT(*) will be '2' for any `id` with both matches.
WHERE `n` = 2
GROUP BY `id`

我没有安装MySQL的方便,所以这没有经过测试,但它是一个最好的猜测,旨在让你在路上。

答案 2 :(得分:0)

这一切都应该有效

SELECT * FROM items i
WHERE EXISTS (
SELECT NULL
FROM blogPostToTags tg
WHERE tg.tagID IN ({tag_comma_separated_values})
AND tg.itemID = i.id
GROUP BY tg.itemID
HAVING COUNT(tg.tagID) = {tag_count}
)

在你的情况下

SELECT * FROM items i
WHERE EXISTS (
SELECT NULL
FROM blogPostToTags tg
WHERE tg.tagID IN (1,2)
AND tg.itemID = i.id
GROUP BY tg.itemID
HAVING COUNT(tg.tagID) = 2
)