MySQL - 连接3个表并将一行作为一列

时间:2016-08-03 15:33:31

标签: mysql laravel-5

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

这是我的情景:

我有两个表:ACCOUNTS,NET_PROCEEDS

ACCOUNTS 表格有:

  1. ACCOUNT_ID
  2. ACCOUNT_NAME
  3. ACCOUNT_DESCRIPTION
  4. NET_PROCEEDS 表格包含:

    1. Net_Proceeds_ID
    2. ACCOUNT_ID
    3. Fiscal_Year
    4. 金额
    5. 现在我的基本sql可以使用此输出连接两个表:

      Account_ID | Account_Name | Account_Description | Fiscal_Year |量

      但我正试图推出这个输出:

      Account_ID | Account_Name | Account_Description | 2016 | 2017年| 2018年| 2019

      fiscal_year将成为值为amount的列。

      有什么想法?我将感谢你的帮助。 由于机密性,我无法共享代码。感谢。

1 个答案:

答案 0 :(得分:0)

这有两种方法,取决于两个表中的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等。