Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

Dapatkan semua anak menurut orang tua dalam kueri mysql

Untuk itu Anda perlu memiliki fungsi yang tersimpan :

DELIMITER $$

DROP FUNCTION IF EXISTS `junk`.`GetFamilyTree` $$
CREATE FUNCTION `GetFamilyTree` (GivenID  VARCHAR(1024)) RETURNS varchar(1024) CHARSET latin1
DETERMINISTIC
BEGIN

    DECLARE rv,q,queue,queue_children,front_id VARCHAR(1024);
    DECLARE queue_length,pos INT;

    SET rv = '';
    SET queue = GivenID;
    SET queue_length = 1;

    WHILE queue_length > 0 DO
        SET front_id = queue;
        IF queue_length = 1 THEN
            SET queue = '';
        ELSE
            SET pos = LOCATE(',',queue) + 1;
            SET q = SUBSTR(queue,pos);
            SET queue = q;
        END IF;
        SET queue_length = queue_length - 1;

        SELECT IFNULL(qc,'') INTO queue_children
        FROM (SELECT GROUP_CONCAT(id) qc
        FROM Table1 WHERE manager = front_id) A;

        IF LENGTH(queue_children) = 0 THEN
            IF LENGTH(queue) = 0 THEN
                SET queue_length = 0;
            END IF;
        ELSE
            IF LENGTH(rv) = 0 THEN
                SET rv = queue_children;
            ELSE
                SET rv = CONCAT(rv,',',queue_children);
            END IF;
            IF LENGTH(queue) = 0 THEN
                SET queue = queue_children;
            ELSE
                SET queue = CONCAT(queue,',',queue_children);
            END IF;
            SET queue_length = LENGTH(queue) - LENGTH(REPLACE(queue,',','')) + 1;
        END IF;
    END WHILE;

    RETURN rv;
END $$

Kemudian Anda dapat menelepon seperti :

SELECT `id`, `manager`,GetFamilyTree(`id`) as children 
from Table1;

Anda juga dapat memiliki filter:

SELECT `id`, `manager`,GetFamilyTree(`id`) as children 
from Table1 where `id` = 'james';

CONTOH FIDDLE




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Secara Otomatis Menangkap Pengecualian untuk PDO di PHP

  2. Bagaimana cara mendapatkan baris terakhir kedua dari database mysql?

  3. Backup dan Restore database MySQL di PHP

  4. Beralih dari SQLite ke MySQL dengan Flask SQLAlchemy

  5. xampp mysql Gagal menginisialisasi struktur multi master