首页 > 解决方案 > 基于多列计算行数

问题描述

我有一个包含相同标签集的多列表,如下所示:

id  |  tagone  |  tagtwo  |  tagthree  |
----------------------------------------
0   |  Action  | Adventure|   Rpg      |
1   |   Rpg    |  Action  |   Indie    |

一行中永远不会有多个相同的标签。我想要的是返回每个标签的元素计数。我希望它独立于它所在的列并计算每一列。像这样:

Action    |2     |
Adventure |1     |
Indie     |1     |
Rpg       |2     |

有没有办法在一个查询中做到这一点?

标签: mysqlsql

解决方案


这是一个糟糕的数据结构。您应该有一个表,每个 id 和每个标签都有一行。

同时,您可以取消此操作:

select tag, count(*)
from ((select id, tagone as tag from t) union all
      (select id, tagtwo as tag from t) union all
      (select id, tagthree as tag from t) 
     ) tt
group by tag

推荐阅读