【问题标题】:Joining two tables and adding column values together连接两个表并将列值加在一起
【发布时间】:2019-08-14 16:30:10
【问题描述】:

我有两个表,在这两个表中我都有一个名为 phone_number 的唯一列,然后是一个名为 spring 的列以及其他 3 个列。弹簧柱有一个数值。该表大约有 3000 行。我有一个包含相同信息但只有大约 300 行的重复表。我想根据 phone_number 唯一列组合两个表的弹簧列的值。

我尝试过 MERGE 和 UNION,但我并不真正了解它们是如何工作的,并且不断出现语法错误。

SELECT
    accountstwo.phone_number, accountstwo.deposit_total, accountstwo.summer, accountstwo.total_remain,
    (
        SUM(accountstwo.spring) + SUM(accountstwonu.spring)
    ) spring
FROM accountstwo LEFT JOIN
     accountstwonu
     ON accountstwonu.phone_number = accountstwo.phone_number
GROUP BY phone_number;

我可以让表加入,但它会创建一个名为 spring 的新列,其中只有组合列总计,并且原始表的其他 2700 行返回为 NULL。我想保留 2700 行数据以及合并其他 300 行数据。

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    这是你想要的吗?

    SELECT a2.phone_number, a2.deposit_total, a2.summer, a2.total_remain,
           (COALESCE(a2.spring, 0) + COALESCE(SUM(a2nu.spring), 0)) as spring
    FROM accountstwo a2 LEFT JOIN
         accountstwonu a2nu
         ON a2.phone_number = a2nu.phone_number
    GROUP BY a2.phone_number, a2.deposit_total, a2.summer, a2.total_remain, a2.spring;
    

    【讨论】:

    • 这正是我想要的,唯一的问题是,如果我离开屏幕或尝试将表格导出为 CSV,那么 JOIN 就会消失。有没有办法让它永久化? - 编辑我从查询中导出的。谢谢!
    • @holodout 。 . .我不确定您所说的“JOIN 消失了。我很高兴该查询对您有用。
    【解决方案2】:

    在两个表中,我都有一个名为 phone_number 的唯一列

    如果phone_number 在两个表中都是唯一的,那么GROUP BYSUM() 没有意义,因为(LEFT)JOIN 结果每个电话号码只能有一行。您可能只需要COALESCE() 用于正确的表,将 NULL 转换为零:

    SELECT
        accountstwo.phone_number,
        accountstwo.deposit_total,
        accountstwo.summer, accountstwo.total_remain,
        accountstwo.spring + COALESCE(accountstwonu.spring, 0) as spring
    FROM accountstwo LEFT JOIN
         accountstwonu
         ON accountstwonu.phone_number = accountstwo.phone_number;
    

    【讨论】:

      猜你喜欢
      • 2010-12-04
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多