Q
Q
Qairat2017-02-06 09:58:40
MySQL
Qairat, 2017-02-06 09:58:40

How to write recursion in mysql?

Hello!
Such a task. We need to find the total population.
It must be done through recursion.
I'm trying to do this:

CREATE PROCEDURE `GetChildrenObjects3`
  (IN `Parent` BIGINT, OUT `total` BIGINT)
BEGIN
  DECLARE population int;
  DECLARE total2 int DEFAULT 0 ;
  DECLARE irows int ;

  SET irows = (SELECT COUNT(d.Population) FROM MDepartments d
    LEFT JOIN Localities l ON d.LocalityId = l.Id WHERE d.ParentId = Parent AND Type = 0);

  IF irows>=1 THEN

    SET total = (SELECT SUM(d.Population) FROM MDepartments d
      LEFT JOIN Localities l ON d.LocalityId = l.Id WHERE d.ParentId = Parent AND Type = 0);

    SELECT d.MOId, SUM(d.Population)  FROM MDepartments d
      LEFT JOIN Localities l ON d.LocalityId = l.Id WHERE d.ParentId = Parent AND Type = 0;

    CALL GetChildrenObjects3(d.MOId);
  ELSE
    SET total = NULL;
  END IF;
END

There are tables, and they can have child objects. It is necessary to go there and summarize the population by parent populations.
Help how?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
ThunderCat, 2017-02-06
@ThunderCat

This decision is in the style - "let's go to the rally on an asphalt skating rink, we know how to manage it, and it doesn't go very fast, we won't fly off the track!".
Select all the values ​​​​by queries into something more programmatic, and twist there, it will be faster, more reliable and more logical.
For example, python, php, java, and almost any language you know will be better than this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question