使用php / mysql按标题和标签显示相关文章

时间:2019-02-16 18:56:14

标签: php mysql

我有这样的文章和标签表

 1. articles
|itemid   |title            |tag
1         |my first post    |hello, world
2         |my second        |world war post
3         |my third post    |testing

the tag is separate either by space or comma

2. tagterm
tag_id| tagterm
1     | hello
2     | world
3     | war
4     | post
5     | testing


3. tag_link
id| tag_id| tag_itemid
1 | 1     | 1
2 | 2     | 1
3 | 2     | 2
and so on 

我想通过标签字段显示所有相关文章,并在可能的情况下显示标题

到目前为止我尝试了什么...不起作用,请帮忙,我是新手

SELECT a1.itemid, GROUP_CONCAT(DISTINCT a2.itemid) AS related_articles 
FROM articles AS a1 
JOIN tag_link AS t1 ON a1.itemid = t1.tag_itemid 
JOIN articles AS a2 ON a2.itemid = t1.tag_itemid GROUP BY a1.itemid

1 个答案:

答案 0 :(得分:1)

尝试一下:

SELECT a1.itemid, a1.title, group_concat(DISTINCT a2.itemid, CONCAT('@',a2.title) SEPARATOR "||") as related_articles
FROM articles AS a1 
JOIN tag_link AS t1 ON a1.itemid = t1.tag_itemid 
JOIN 
    (SELECT a1.itemid as itemid, a1.title as title, t1.tag_id as tag_id
        FROM articles AS a1 
        JOIN tag_link AS t1 ON a1.itemid = t1.tag_itemid) as `a2`
    ON a2.tag_id=t1.tag_id
WHERE a2.itemid != a1.itemid
GROUP BY a1.itemid

实时DEMO