"http://sqlfiddle.com/#!9/add59/1"> link
Node that your categories were a tree with only two levels, so all the looks are directly connected to the root, in this case a simple LEFT JOIN
with COALESCE
should work.
SELECT
id,
desc_cat,
SUM(value)
FROM (
SELECT
COALESCE(CatParent.id, Category.id) id,
COALESCE(CatParent.desc_cat, Category.desc_cat) desc_cat,
CashBook.value
FROM CashBook
JOIN Category ON CashBook.category_id = Category.id
LEFT JOIN Category AS CatParent ON Category.parent_id = CatParent.id
) AS CatParent
GROUP BY id, desc_cat
But this approach will only work in this situation, if your tree goes deeper, you will have problems ... for example ... if your Category
table has the following data:
| id | desc_cat | parent_id |
|----|---------------------|-----------|
| 26 | Categoria 1 | (null) |
| 27 | Sub Categoria 1.1 | 26 |
| 28 | Sub Categoria 1.1.1 | 27 |
| 29 | Sub Categoria 1.1.2 | 27 |
| 30 | Sub Categoria 1.2 | 26 |
| 31 | Sub Categoria 1.2.1 | 30 |
| 32 | Sub Categoria 1.2.2 | 30 |
I even tried to emulate a recursive query using CTE
using View
or a Function
with MySQL
... but I could not do it in SQLFiddle
, I believe MySQL
does not support this type of structure.
You can still use WHILE
to try to do something, but your MySQL
will not be able to infer an execution plan, your query will be complex. I would only advise you to do this for a scheduled JOB.
But as this data is going to be consumed in PHP, the ideal thing is to do this type of direct control in PHP ... unfortunately I do not know the PHP enough to give you an example, however I can update this answer with a snippet of Code in C # or JavaScript, then you could make a port from this logic to PHP.