如何获得标记文章?

时间:2012-03-23 09:21:06

标签: mysql ruby-on-rails

我有三张桌子:

articles(id int)
tags(id int, name varchar(255))
articles_tags(article_id, tag_id)

我想找到属于tag1tag2的所有文章,我如何用MySQL编写一个好的性能查询?或者有一种设计表格的好方法吗?

现在,我正在使用Sphinx,但Sphinx不支持订购订单属性列的更新索引。

1 个答案:

答案 0 :(得分:2)

SELECT a.* FROM articles a 
INNER JOIN articles_tags at ON a.id=at.article_id
INNER JOIN tags t ON t.id=at.tag_id
WHERE t.name IN ('tag1', 'tag2)
GROUP BY a.id
HAVING count(a.id) >= 2;

您应该添加标记名称并为其编制索引。

此外,您可以考虑使用标记名称作为标记表的主键,删除标记ID。这样你只需要加入article_tags表:

SELECT a.* FROM articles a 
INNER JOIN articles_tags at ON a.id=at.article_id
WHERE at.tag_name IN ('tag1', 'tag2)
GROUP BY a.id
HAVING count(a.id) >= 2;
相关问题