MySQL:合并两个表,某些列不同

时间:2019-01-23 10:08:08

标签: mysql database sqlite

我要合并两个sql表的要求

  • game_data1列:安装日期,源,安装,支出,CPI
  • game_data2列:安装日期,购买日期,来源,收入
  • 合并表(想要这样):安装日期,来源,安装,支出,CPI,购买日期,收入

我已经阅读了诸如this之类的其他SO答案,因此通过阅读这些类型的答案,我进行了查询

SELECT s.install_date, s.source, s.installs, s.Spending, s.CPI, r.install_date, r.purchase_date, r.source, r.revenue 

FROM game_data as s

JOIN game_data2 as r ON r.install_date = s.install_date AND r.source = s.source

它应该使一个install_date列和一个source列,但是使它成为两个单独的列,我不知道这是怎么回事

  

game_data1(我要合并的表1)

enter image description here

  

game_data2(我要合并的table2)

enter image description here

我已经写了一个更改日期格式的函数,所以不要介意日期格式

  

结果

+--------------+----------+----------+----------+----------+--------------+---------------+----------+---------+
| install_date | source   | installs | Spending | CPI      | install_date | purchase_date | source   | revenue |
+--------------+----------+----------+----------+----------+--------------+---------------+----------+---------+
| 2015-03-01   | facebook |    10000 |     6000 |      0.6 | 2015-03-01   | 2015-03-01    | facebook |     600 |
| 2015-03-01   | facebook |    10000 |     6000 |      0.6 | 2015-03-01   | 2015-03-01    | facebook |     600 |
| 2015-03-01   | facebook |    10000 |     6000 |      0.6 | 2015-03-01   | 2015-03-02    | facebook |     550 |
| 2015-03-01   | facebook |    10000 |     6000 |      0.6 | 2015-03-01   | 2015-03-02    | facebook |     550 |
| 2015-03-01   | facebook |    10000 |     6000 |      0.6 | 2015-03-01   | 2015-03-03    | facebook |     500 |
| 2015-03-01   | facebook |    10000 |     6000 |      0.6 | 2015-03-01   | 2015-03-03    | facebook |     500 |
| 2015-03-01   | facebook |    10000 |     6000 |      0.6 | 2015-03-01   | 2015-03-04    | facebook |     450 |

我想按原样合并这些表,但是我想install_date和source应该是一列而不是两列

如果有人想获得帮助,我觉得获得帮助很有用,但无法正确理解:Link

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

您只需在查询中指定一次install_datesource

SELECT 
    s.install_date,
    s.source,
    s.installs,
    s.Spending,
    s.CPI,
    r.purchase_date,
    r.revenue
FROM
    game_data AS s
        JOIN
    game_data2 AS r ON r.install_date = s.install_date
        AND r.source = s.source;

答案 1 :(得分:0)

选择s.install_date,s.source,s.installs,s.Spending,s.CPI,r.purchase_date,r.source,r.revenue

FROM game_data as s

在r.install_date = s.install_date和r.source = s.source上r启用INNER JOIN game_data2