SQL用于简单相关性排名

时间:2019-04-17 18:09:28

标签: mysql sql union

我有3个表:person_tag(个人ID,标签),interest_tag(兴趣ID,标签),skill_tag(skill_id,标签)。就像我想为兴趣和技能使用一张标签表一样,我需要将它们分开。以下示例数据:

+-----------+-------------+
| 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将成为我的朋友,但不太确定如何编写查询。有人有建议吗?

2 个答案:

答案 0 :(得分:0)

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

P.S。顺便说一句,您不需要person_tag表。

答案 1 :(得分:0)

是的工会可以工作

select interest_id as id,count(*) as score, 'Interest' as typ from interest group by interest_id
union
select skill_id as id,count(*) as score, 'Skill' as typ from skill group by skill_id;
相关问题