在mysql中查找相关主题?

时间:2014-06-20 14:39:25

标签: mysql sql

我的数据库如下:

Post {id, title}
Topic {id, name}
Post_Topic {PostId, TopicId}

由于每个帖子可能有很多主题,因此我希望根据它们在帖子中出现的次数来获取相关主题。例如:

post 1 has topics {database, mysql, mobile}
post 2 has topics {database, mysql, android}
post 3 has topics {database, mysql, algorithm}
post 4 has topics {database, algorithm, web programming}

根据以上数据,如果输入为database,则应按顺序显示相关主题:

mysql (appears 3 times with database)
algorithm (appears 2 times with database)
android
mobile

如何编写sql来实现它?

2 个答案:

答案 0 :(得分:1)

你可能会找到一种更好的方法(两次条件不太好),但是,通过join和exists子句,你可以获得你想要的东西。

select t_id, t.title, count(*) as cnt
from post_topic pt
join topic t on t.id = pt.t_id

where exists (select null
              from post_topic pt1
              join topic t1 on pt1.t_id = t1.id
              where t1.title = 'database'  and p_id = pt.p_id)
and t.title <> 'database'
group by  t_id, t.title
order by cnt desc;

请参阅Sqlfiddle

答案 1 :(得分:0)

试试这个

SELECT topic_name FROM (SELECT COUNT(*) as cnt, t.id, t.topic_name 
FROM Topic t 
JOIN Post_Topic pt ON (pt.TopicId = t.id)
WHERE pt.PostId IN (
    SELECT pt2.PostId FROM Post_Topic pt2 JOIN Topic t2 ON (pt2.TopicId = t2.id) WHERE t2.topic_name= 'database')
GROUP BY t.id, t.topic_name) as S
WHERE topic_name != 'database'
ORDER BY cnt DESC