mysql - 加入/合并具有相同列名的多个表
问题描述
我想分别从下面的 SQLFiddle 加入三个表
http://sqlfiddle.com/#!9/5dd558/4
现在我想根据日期和品牌从这个表中创建一个表。就像,我想要这种方式的数据
日期,品牌,系列, Table_1_Viewers , Table_2_Viewers , Table_2_Viewers
如果表中的数据不匹配,则该字段应为空。
我做了什么
SELECT h.*,
a.`amazon_viewers` AS "Table_1_Viewers",
n.`views` AS "Table_2_Viewers",
FROM `Table-1` h
LEFT JOIN `Table-2` a
ON h.`date` = a.`date`
AND h.`brand` = a.`brand`
LEFT JOIN `Table-3` n
ON h.`date` = n.`date`
AND h.`brand` = n.`brand`
显然我是从表 1 中选择数据,所以它只会显示表 1 中的品牌列,但是我怎样才能在一列中获取所有表的品牌列名称并合并这些表。??
我想要的输出...
| 日期 | 品牌 | 系列 | Table_1_Viewers | Table_2_Viewers | Table_3_Viewers | |:---------:|:--------:|:-------------:|:-------- --------:|:---------------:|:----------------:| | 2018 年 12 月 1 日 | 测试 | 测试系列 | 100 | | | | 2018 年 10 月 15 日 | 音乐电视 | 得到 | 1000 | | 1000 | | 2018 年 12 月 1 日 | 测试 | 维京人 | 485632 | 856325 | | | 2018 年 12 月 1 日 | 测试 | 另一个系列 | | 200 | | | 2018 年 10 月 15 日 | 离岸博彩 | 得到 | | 1000 | | | 2019 年 7 月 1 日 | No_Match | 测试系列 | | | 100 | | 2018 年 12 月 1 日 | 测试5 | 维京人 | | | 953022 |
解决方案
您可以union all
使用聚合:
select t.Date, t.Brand, t.Series_name,
sum(case when table_view = 't1' then amazone_viewer else 0 end) as Table_1_Viewers,
. . .
from (select h.date, h.brand, h.series_name, h.amazone_viewer, 't1' as table_view
from `Table-1` h union all
select h1.date, h1.brand, h1.series, h1.viewes, 't2'
from `Table-2` h1 union all
. . .
) t
group by t.Date, t.Brand, t.Series_name;
推荐阅读
- python - 如何在 Pytorch 中有效地连接两层的输出?
- python - 如何在指数级大列表中找到第 k 个最大的元素?
- javascript - 创建函数 REGEX 进行优化
- laravel - DocuSign:将我从信封中获得的文件存储在 Laravel
- node.js - Strapi-provider-upload-cloudinary install 但strapi说模块没有
- android - Viewmodel 数据在旋转时丢失
- javascript - 在Javascripts中删除字符串的最后一部分
- javascript - 从字符串中删除 html 属性
- javascript - DataTable 有限行
- c++ - glfwSwapBuffers(窗口); 失败并抛出异常