gpt4 book ai didi

mysql - 连接/合并具有相同列名的多个表

转载 作者:行者123 更新时间:2023-11-29 09:26:29 26 4
gpt4 key购买 nike

我想分别从下面的SQLFiddle连接三个表

http://sqlfiddle.com/#!9/5dd558/4

现在我想根据日期和品牌从该表创建一个表。就像,我想要这种方式的数据

日期品牌系列Table_1_ViewersTable_2_ViewersTable_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 中的品牌列,但如何在一列中获取所有表的品牌列名称并合并这些表。??

我想要的输出...

|    Date    |   Brand  |     Series     | Table_1_Viewers | Table_2_Viewers | Table_3_Viewers ||:----------:|:--------:|:--------------:|:---------------:|:---------------:|:---------------:||  12/1/2018 |   TEST   |   TEST_SERIES  |       100       |                 |                 || 10/15/2018 |    MTV   |       GOT      |       1000      |                 |       1000      ||  12/1/2018 |   TEST   |     Viking     |      485632     |      856325     |                 ||  12/1/2018 |   TEST   | Another Series |                 |       200       |                 || 10/15/2018 |   POGO   |       GOT      |                 |       1000      |                 ||  7/1/2019  | No_Match |   TEST_SERIES  |                 |                 |       100       ||  12/1/2018 |  TEST-5  |     Viking     |                 |                 |      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;

关于mysql - 连接/合并具有相同列名的多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59527734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com