2014-01-14 81 views
0

我有两个表,一个连接到第一个与n:1的关系。如何通过标签名称获取相关文章?

我想通过在发布文章时插入标签名称来检索相关文章。

我的表结构表示如下:

articles

id | article_title | article_content 
----+-----------------+---------------- 
1 | title one  | info goes here 
2 | title two  | info goes here 
3 | title three | info goes here 

article_tags

tag_id | article_id | tag_name 
-------+--------------+---------------- 
    1 |  1  | health 
    2 |  1  | information 
    3 |  2  | how-to 
    4 |  3  | how-to 
    5 |  3  | health 
    6 |  3  | network 
    7 |  1  | network 

我无法弄清楚如何被那些为tag_names加例如获得相关的文章。

article_id 1有health第3条也有共同点。

article_id 2 has how-to which article 3 also has common。

我曾尝试以下,但它并没有真正涉及到的标签名称,因为我无法弄清楚如何将连接tag_names加..

SELECT * 
FROM articles 
LEFT JOIN article_tags ON articles.article_uid = article_tags.article_id 
LIMIT 4 

回答

3
SELECT a1.id, GROUP_CONCAT(DISTINCT a2.id) AS related_articles 
FROM articles AS a1 
JOIN article_tags AS t1 ON a1.id = t1.article_id 
JOIN article_tags AS t2 ON t2.tag_name = t1.tag_name AND t2.article_id != t1.article_id 
JOIN articles AS a2 ON a2.id = t2.article_id 
GROUP BY a1.id 

DEMO

+0

这是有点困惑,无法理解所有事情,每个人都在做什么,但我终于明白了,再次感谢Barmar。 – iBrazilian2

相关问题