我的数据库如下:
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 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;
关于mysql - 在mysql中找到相关主题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24329853/