mysql - SQL 进行简单的相关性排名

标签 mysql sql union

我有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 会是我的 friend ,但不太确定如何编写查询。有人有建议吗?

最佳答案

您可以将union allgroup 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

附注顺便说一句,您不需要 person_tag 表。

关于mysql - SQL 进行简单的相关性排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55733636/

相关文章:

mysql - 如何使用 mysql 获取最近 5 天的总计?

mysql - 修复自增mysql

java - 连接mysql的jar无法运行

MYSQL/查询 : How to make table rows into column

mysql - UNION SELECT 错误 1064 但如果单独执行则有效

javascript - 使用 lodash 合并 2 个数组

sql - mysql 显示 group by 语句的空值

sql - 如何在SQL Server中的存储过程中使用between

mysql - SQL Count() child Rows 基于来自 Parent 的值

sql - 使用的 SELECT 语句具有不同的列数