mysql - 用于简单相关性排名的 SQL
问题描述
我有3个表:person_tag(person_id,tag),interest_tag(interest_id,tag),skill_tag(skill_id,tag)。就像我希望有一个兴趣和技能的标签表一样,我需要将它们分开。下面的示例数据:
+-----------+-------------+
| person_id | tag |
+-----------+-------------+
| 1 | x |
| 1 | y |
| 1 | z |
+-----------+-------------+
+-------------+-------------+
| interest_id | tag |
+-------------+-------------+
| 10 | x |
| 20 | y |
| 20 | z |
+-------------+-------------+
+-------------+-------------+
| skill_id | tag |
+-------------+-------------+
| 100 | x |
| 100 | y |
| 100 | z |
| 900 | a |
+-------------+-------------+
我想编写一个查询,该查询将根据给定 person_id(例如 1)的相关性返回如下结果。注意“a”没有出现在下面的结果中:
+-------------+-------------+-------------+
| id | typ | score |
+-------------+-------------+-------------+
| 100 | skill | 3 |
| 20 | interest | 2 |
| 10 | interest | 1 |
+-------------+-------------+-------------+
我怀疑 UNION 将成为我的朋友,但不太确定如何编写查询。有人有建议吗?
解决方案
您可以使用union all
withgroup by
表达式
select skill_id , 'skill' as typ, count( skill_id ) as score
from skill_tag
group by skill_id
union all
select interest_id , 'interest' as typ, count(interest_id) as score
from interest_tag
group by interest_id
order by score desc
PS 顺便说一句,你不需要person_tag
桌子。
推荐阅读
- css - Webpack 4 splitChunks 生成多个 css
- c++ - 如何在没有 std::move 的情况下移动临时对象
- javascript - 猫头鹰旋转木马像帐篷一样奔跑
- orbeon - 获取组件中的配置值
- javascript - 当 app-advanced-select 存在时,专注于输入以发送键
- tableau-api - Tableau 中带条件的窗口总和
- python - 如何在 Python 中实现类似#define 的功能来隔离不同的代码片段
- ruby - 在原点的给定半径范围内和外部生成随机坐标
- java - 忽略“接受”标题时返回“文本/纯文本”
- telegram - 电报护照。使用命令“/setpublickey”在哪里?