创建将 4 个元组汇总为一个的 VIEW
Posted
技术标签:
【中文标题】创建将 4 个元组汇总为一个的 VIEW【英文标题】:Create VIEW that summarizes 4 tuples in one 【发布时间】:2019-10-28 14:40:04 【问题描述】:我想创建一个重新格式化我的数据的 SQL VIEW
那是我创建的表格。由于端口需要是唯一的,我将它们放在一列中:
MariaDB [admindb]> select * from table_tennant;
+-------+----------+--------------+----------------+
| port | protocol | tennant_name | tennant_domain |
+-------+----------+--------------+----------------+
| 10000 | https | test | test.test.de |
| 10001 | smtp | test | test.test.de |
| 10002 | mgmt | test | test.test.de |
| 10003 | solr | test | test.test.de |
| 10010 | https | test2 | test2.test.de |
| 10011 | smtp | test2 | test2.test.de |
| 10012 | mgmt | test2 | test2.test.de |
| 10013 | solr | test2 | test2.test.de |
+-------+----------+--------------+----------------+
每个租户的 4 行应该显示为一个,像这样
+----------------+--------------+------------+-----------+-----------+-----------+
| tennant_domain | tennant_name | https_port | smtp_port | mgmt_port | solr_port |
+----------------+--------------+------------+-----------+-----------+-----------+
| test.test.de | test | 10000 | 10001 | 10002 | 10003 |
+----------------+--------------+------------+-----------+-----------+-----------+
这仅适用于表中的一个租户。如果我输入第二个,我的 SELECT 视图语句返回多个结果,这会导致错误。
MariaDB [admindb]> select * from view_ausgabe;
ERROR 1242 (21000): Subquery returns more than 1 row"
这是我的 VIEW 定义
MariaDB [admindb]> CREATE VIEW view_ausgabe AS SELECT tennant_domain, tennant_name,
-> (SELECT port from table_tennant WHERE protocol = 'https' GROUP BY tennant_name AND tennant_domain) AS https_port,
-> (SELECT port from table_tennant WHERE protocol = 'smtp' GROUP BY tennant_name AND tennant_domain) AS smtp_port,
-> (SELECT port from table_tennant WHERE protocol = 'mgmt' GROUP BY tennant_name AND tennant_domain) AS mgmt_port,
-> (SELECT port from table_tennant WHERE protocol = 'solr' GROUP BY tennant_name AND tennant_domain) AS solr_port
-> FROM table_tennant GROUP BY tennant_name;
如何在 VIEW 中为每个租户创建一个新行?
感谢您的帮助。 安德烈
【问题讨论】:
该技术称为“旋转”。 【参考方案1】:使用条件聚合:
create view view_ausgabe as
select
tennant_domain,
tennant_name,
max(case when protocal = 'https' then port end) https_port,
max(case when protocal = 'smtp' then port end) smtp_port,
max(case when protocal = 'mngt' then port end) mngt_port,
max(case when protocal = 'solr' then port end) solr_port
from mytable
group by tennant_domain, tennant_name
【讨论】:
以上是关于创建将 4 个元组汇总为一个的 VIEW的主要内容,如果未能解决你的问题,请参考以下文章