mysql - 在mysql中找到相关主题?

标签 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}

根据以上数据,如果输入的是数据库,那么相关主题应该按顺序显示:

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;

参见Sqlfiddle

关于mysql - 在mysql中找到相关主题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24329853/

相关文章:

mysql - 如果其他表中存在值,则限制插入/更新

mysql - 此集合实例上不存在属性 [日期]

mysql - 2个多对多关系的数据库建模

mysql - 有什么方法可以更改此 SQL 查询,使其不返回任何包含空格的结果?

sql - 根据存在情况更新元素或将元素插入到 xml 列中

php用redis实现一个队列

mysql - 定义日期属性

sql - ORA-01791 : not a SELECTed expression PL SQL

php - 查询多列php/mysql

sql - 如何使用 MS SQL 根据标签、类别、国家/地区对新闻进行分组