在mysql中查找相关主题?

在mysql中查找相关主题?,mysql,sql,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 {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}
基于上述数据,如果输入为数据库,则相关主题应按顺序显示:

mysql (appears 3 times with database)
algorithm (appears 2 times with database)
android
mobile
如何编写sql来实现这一点?

试试这个

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

您可能会找到一个更好的方法,将一个条件重复两次并不好,但是,通过一个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;

参见

内部连接和计数您想要的结果似乎是错误的:web编程1次也应该返回,不是吗?不是,这只是基本的想法。我也会结合其他条件,可能会限制至少3次出现的时间…你有什么建议更好的方式来确定相关的主题?