My database has a structure like this:

‘Movimientos’ table keeps records of all charges and payments of my system.
‘Cargos’ table keeps some metadata of each charge on ‘Movimientos’ and ‘Abonos’ table keeps some metadata of each payment on ‘Movimientos’.
How do I write a query which sum all records in ‘Movimientos’ where ‘Abonos.tipo_abono’ and ‘Cargos.tipo_cargo’ have some criteria?
I have a query that already sum ‘Movimientos’ but I can’t add the part where ‘Abonos’ and ‘Cargos’ tables add more criteria.
SELECT SUM(M.monto) as monto, SUM(M.interes) as interes, SUM(M.iva) as iva, SUM(M.capital) as capital
FROM movimientos AS M
JOIN acreditados AS A ON A.id_acreditado = M.id_acreditado
JOIN creditos AS C ON C.id_credito = A.id_credito
WHERE C.id_credito = 29
Let’s say I want modify the last query to just sum records where ‘Abono.tipo_abono’=1 and ‘Cargos.tipo_cargo’=1, how do I do it?
If your relationships are one-to-one, you can just join the tables in and filter by your criteria. If related records are always present, make it an inner join. If the related tables may not have records, it should be a
LEFT OUTER JOINwith the criteria specified in theJOINrather than theWHERE.However, if your relationships are many-to-one, this will affect your sum by including multiple
movimientosrows. Use anEXISTSclause instead: