Join

如何在此程式碼中將右連接添加到其他表

  • August 16, 2020

我有這個程式碼執行:

SELECT IDLOTE,
      SUM(CASE WHEN FECHAMOVTO='2020-01-01'
               THEN cargo
               ELSE 0
               END) *4 as saldo,
      SUM(CASE WHEN FECHAMOVTO>'2019-12-31' and (idconcepto=2 or idconcepto=4 or idconcepto=22 or idconcepto=23 or idconcepto=24)
               THEN cargo
               ELSE 0
               END) as saldo2,
      SUM(CASE WHEN FECHAMOVTO<='2019-12-31'  
               THEN cargo-abono
               ELSE 0
               END) as saldo3,
       SUM(CASE WHEN FECHAMOVTO<'2020-01-01' 
               THEN cargo-abono
               ELSE 0
               END) as saldo4,
       SUM(CASE WHEN FECHAMOVTO>='2020-01-01' and (idconcepto=2 or idconcepto=4 or idconcepto=22 or idconcepto=23)
               THEN cargo
               ELSE 0
               END) as saldo5    
FROM polizamovtos 
GROUP BY IDLOTE
HAVING SUM(cargo) > SUM(abono)

所以,我需要用表propietarios在idlote上添加右連接

我嘗試使用此程式碼:

SELECT IDLOTE,
  SUM(CASE WHEN FECHAMOVTO='2020-01-01'
           THEN cargo
           ELSE 0
           END) *4 as saldo,
  SUM(CASE WHEN FECHAMOVTO>'2019-12-31' and (idconcepto=2 or idconcepto=4 or idconcepto=22 or idconcepto=23 or idconcepto=24)
           THEN cargo
           ELSE 0
           END) as saldo2,
  SUM(CASE WHEN FECHAMOVTO<='2019-12-31'  
           THEN cargo-abono
           ELSE 0
           END) as saldo3,
   SUM(CASE WHEN FECHAMOVTO<'2020-01-01' 
           THEN cargo-abono
           ELSE 0
           END) as saldo4,
   SUM(CASE WHEN FECHAMOVTO>='2020-01-01' and (idconcepto=2 or idconcepto=4 or idconcepto=22 or idconcepto=23)
           THEN cargo
           ELSE 0
           END) as saldo5    
FROM polizamovtos t1
INNER JOIN asignarlotes on asignarlotes.IDLOTE=polizamovtos.idlote
GROUP BY IDLOTE
HAVING SUM(cargo) > SUM(abono)

對於第二張表,mysql不知道該選擇哪一列,當它們像IDIOTE一樣具有相同的名稱時,因此選擇一個。

我將 polizamovtos 的別名更改為p並賦予aasignarlotes,這樣更易於閱讀,並且您始終知道要使用哪個表

SELECT p.IDLOTE,
  SUM(CASE WHEN FECHAMOVTO='2020-01-01'
           THEN cargo
           ELSE 0
           END) *4 as saldo,
  SUM(CASE WHEN FECHAMOVTO>'2019-12-31' and (idconcepto=2 or idconcepto=4 or idconcepto=22 or idconcepto=23 or idconcepto=24)
           THEN cargo
           ELSE 0
           END) as saldo2,
  SUM(CASE WHEN FECHAMOVTO<='2019-12-31'  
           THEN cargo-abono
           ELSE 0
           END) as saldo3,
   SUM(CASE WHEN FECHAMOVTO<'2020-01-01' 
           THEN cargo-abono
           ELSE 0
           END) as saldo4,
   SUM(CASE WHEN FECHAMOVTO>='2020-01-01' and (idconcepto=2 or idconcepto=4 or idconcepto=22 or idconcepto=23)
           THEN cargo
           ELSE 0
           END) as saldo5    
FROM polizamovtos p
INNER JOIN asignarlotes a on a.IDLOTE=p.idlote
GROUP BY p.IDLOTE
HAVING SUM(cargo) > SUM(abono)

引用自:https://dba.stackexchange.com/questions/273807