2012-03-23 70 views
0

我有三个表:如何获得标签文章?

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

我想找到属于tag1tag2所有文章,我怎样书写与MySQL有着不错的表现查询?或者是否有设计表格的好方法?

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

回答

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; 
+0

好吧,我的答案跳动。我必须学习关系表。 – nickw444 2012-03-23 09:33:31

+0

@barsju,您的查询不支持查找同时属于tag1和tag2的文章! – Neo 2012-03-23 09:33:39

+0

哦。我看到我的不好..让我编辑我的答案 – barsju 2012-03-23 09:35:56