【问题标题】:MySQL - Joining 3 Tables and Make one row as a columnMySQL - 连接 3 个表并将一行作为一列
【发布时间】:2016-12-09 10:23:03
【问题描述】:

我试图在现有线程上寻求帮助,但我发现自己因为答案而迷失了方向。

这是我的场景:

我有两个表:ACCOUNTS、NET_PROCEEDS

ACCOUNTS 表有:

  1. Account_ID
  2. Account_Name
  3. Account_Description

NET_PROCEEDS 表有:

  1. Net_Proceeds_ID
  2. Account_ID
  3. Fiscal_Year
  4. 金额

现在我的基本 sql 可以用这个输出连接两个表:

Account_ID |帐户名 |账户_描述 |财政年度 |金额

但我正在尝试输出这个输出:

Account_ID |帐户名 |账户_描述 | 2016 | 2017 | 2018 | 2019

会计年度将成为一列,其值为金额。

有什么想法吗?我会感谢你的帮助。 P.S 由于保密原因,我不能分享代码。谢谢。

【问题讨论】:

    标签: mysql laravel-5


    【解决方案1】:

    这里有 2 种方法,具体取决于 Account_ID 在两个表中是否唯一。 更快的方法(如果 Account_ID 对于每个表都是唯一的):

    SELECT A.*, N16.Amount as Amount_2016 
    , N17.Amount as Amount_2017 
    , N18.Amount as Amount_2018 
    , N19.Amount as Amount_2019 
    FROM ACCOUNTS A 
    LEFT JOIN NET_PROCEEDS N16 ON N16.Account_ID = A.Account_ID AND N16.Fiscal_Year = '2016'
    LEFT JOIN NET_PROCEEDS N17 ON N17.Account_ID = A.Account_ID AND N17.Fiscal_Year = '2017'
    LEFT JOIN NET_PROCEEDS N18 ON N18.Account_ID = A.Account_ID AND N18.Fiscal_Year = '2018'
    LEFT JOIN NET_PROCEEDS N19 ON N19.Account_ID = A.Account_ID AND N19.Fiscal_Year = '2019'
    

    更安全的方式(如果 Account_ID 不是/可能不是每个表唯一的):

    SELECT A.*, (SELECT SUM(N16.Amount) FROM NET_PROCEEDS N16 ON N16.Account_ID = A.Account_ID AND N16.Fiscal_Year = '2016') as Amount_2016 
    , (SELECT SUM(N17.Amount) FROM NET_PROCEEDS N17 ON N17.Account_ID = A.Account_ID AND N17.Fiscal_Year = '2017') as Amount_2017
    , (SELECT SUM(N18.Amount) FROM NET_PROCEEDS N18 ON N18.Account_ID = A.Account_ID AND N18.Fiscal_Year = '2018') as Amount_2018 
    , (SELECT SUM(N19.Amount) FROM NET_PROCEEDS N19 ON N19.Account_ID = A.Account_ID AND N19.Fiscal_Year = '2019') as Amount_2019 
    FROM ACCOUNTS A 
    

    如果您在 Account_ID 不唯一时使用第一个,它将为 Account_ID 的每个重复实例创建多行,这将与任何 SUM 或 COUNT 等混淆。

    【讨论】:

    • 谢谢你,但 net_proceeds 表中可能有很多 account_ID。
    • 嗨,是的,这就是您使用第二个查询的原因
    猜你喜欢
    • 2013-06-30
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多