使用联合选择构建 MySQL 视图
Posted
技术标签:
【中文标题】使用联合选择构建 MySQL 视图【英文标题】:Building a MySQL view with union of selects 【发布时间】:2017-05-15 12:07:02 【问题描述】:我有一个具有以下结构的表: 列名称是指标(MT_NAME、MT_ADDRESS、MT_PHONE 等),行是来自该事件的指标的值/分数(0、6、8、9、10)。 像这样:
+---------+------------+----------+
| MT_NAME | MT_ADDRESS | MT_PHONE |
+---------+------------+----------+
| 0 | 9 | 6 |
| 6 | 10 | 0 |
| 8 | 10 | 0 |
+---------+------------+----------+
我想构建一个包含 3 列的视图:一列包含表列的名称,一列包含该列的不同值,另一列包含这些值在该列中出现的频率。 像这样的:
+------------+----------+-------+
| LEGEND | CATEGORY | VALUE |
+------------+----------+-------+
| MT_NAME | 0 | 1 |
| MT_NAME | 6 | 1 |
| MT_NAME | 8 | 1 |
| MT_ADDRESS | 9 | 1 |
| MT_ADDRESS | 10 | 2 |
| MT_PHONE | 0 | 2 |
| MT_PHONE | 6 | 1 |
+------------+----------+-------+
有人可以帮忙吗?
【问题讨论】:
【参考方案1】:你可以使用union all
:
select 'MT_NAME' as legend, mt_name as category, count(*) as frequency
from t
group by mt_name
union all
select 'MT_ADDRESS' as legend, mt_address as category, count(*) as frequency
from t
group by mt_name
union all
select 'MT_PHONE' as legend, mt_phone as category, count(*) as frequency
from t
group by mt_name;
【讨论】:
非常感谢!以上是关于使用联合选择构建 MySQL 视图的主要内容,如果未能解决你的问题,请参考以下文章