Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

I have 2 table master coa and coa transaction in MySQL like this,

master :

 id | coa  | id_parent | 
----+------+-----------+
  1 | 1    |  NULL     |
  2 | 11   |   1       |
  3 | 111  |   2       |
  4 | 12   |   1       |
  5 | 121  |   4       |
  6 | 122  |   4       |

transaction :

 id | debit | credit | 
----+-------+--------+
  3 |     0 |      5 |
  3 |     0 |     20 |
  5 |    10 |      0 |
  5 |    15 |      0 |
  5 |     5 |      0 |
  6 |     0 |      5 |

The depth level child-parent is unlimited. What i want to get is view like this,

 id | coa  | debit | credit | 
----+------+-------+--------+
  1 | 1    |    20 |     30 |
  2 | 11   |     0 |     25 |
  3 | 111  |     0 |     25 |
  4 | 12   |    20 |      5 |
  5 | 121  |    20 |      0 |
  6 | 122  |     0 |      5 |

How can i accomplish this using SELECT ? so far i only can get debit credit only the lowest depth using GROUP SUM and join. Any suggestion?

share|improve this question

1 Answer 1

The following query:

SELECT  m1.id, m1.coa, IFNULL(sum(t.debit), 0) as debit, 
        IFNULL(sum(t.credit), 0) as credit 
FROM master m1 
JOIN master m2 
    ON m2.coa like CONCAT(m1.coa, '%') 
LEFT JOIN transaction t 
    ON m2.id = t.id 
GROUP BY m1.id;

Returns the following for me:

+----+------+-------+--------+
| id | coa  | debit | credit |
+----+------+-------+--------+
|  1 | 1    |    30 |     30 |
|  2 | 11   |     0 |     25 |
|  3 | 111  |     0 |     25 |
|  4 | 12   |    30 |      5 |
|  5 | 121  |    30 |      0 |
|  6 | 122  |     0 |      5 |
+----+------+-------+--------+
6 rows in set (0.00 sec)

Please note that all transactions are or have 1 as parent, so I am not sure why you didn't add up your third transaction.

My query returns 1 row for each id, even if it has not transactions (with credit and debit 0). Change the LEFT JOIN to a JOIN and get rid of the IFNULLs if you only want ids with movements.

Also please be aware that this query will be very badly improved in performance with indexes, and that I would recommend rethinking an alternative structure if the query is frequent and any of the two tables is very tall.

share|improve this answer
1  
Nice. I think you should add that you are basically using the materialized path that is stored in the coa column and not at all the adjacency list that is stored in the id_parent. –  ypercube Aug 4 at 7:38
    
Or I can just upvote you for visibility because you are 100% right. –  jynus Aug 4 at 7:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.