Search
 
SCRIPT & CODE EXAMPLE
 

SQL

mysql get nested records

DROP PROCEDURE IF EXISTS famsubtree;
DELIMITER go
CREATE PROCEDURE famsubtree( root INT )
BEGIN
  DROP TABLE IF EXISTS famsubtree;
  CREATE TABLE famsubtree
    SELECT childID, parentID, 0 AS level
    FROM familytree
    WHERE parentID = root;
  ALTER TABLE famsubtree ADD PRIMARY KEY(childID,parentID);
  REPEAT
    INSERT IGNORE INTO famsubtree
      SELECT f.childID, f.parentID, s.level+1
      FROM familytree AS f
      JOIN famsubtree AS s ON f.parentID = s.childID;
  UNTIL Row_Count() = 0 END REPEAT;
END;
go
DELIMITER;

And use to query:

call famsubtree(1);       -- from the root you can see forever
SELECT Concat(Space(level),parentID) AS Parent, Group_Concat(childID ORDER BY childID) AS Child
FROM famsubtree
GROUP BY parentID;
Comment

PREVIOUS NEXT
Code Example
Sql :: kill slow queries mysql 
Sql :: rollback to name in sql 
Sql :: mysql cannot access localhost 
Sql :: Raw into column 
Sql :: mysql procedure between two tables 
Sql :: find Overlapping sql 
Sql :: azure sql server check foreign key 
Sql :: extract sql from query object sqlalchemy 
Sql :: distinct data types in a table sql query 
Sql :: sql group by and having 
Sql :: do you know sql 
Sql :: how to make full text search dynamic in mysql 
Sql :: fill a coulmn with a certain value sql 
Sql :: joins and views sql 
Sql :: mysql join table with a text columns with ids splited by char 
Sql :: SOQL Parent to child 
Sql :: distinct 
Sql :: sql start with vowels 
Sql :: drop-toys-table 
Sql :: postgres docs /copy metacomand 
Sql :: ring get column value from the fetched row using the odbc_getdata() 
Sql :: SQL Creating a Table to Store Date and Time 
Sql :: Update Multiple Values in a Row 
Sql :: learn sqlite dart 
Sql :: inner join multiple conditions 
Sql :: ring MySQL Create Database 
Sql :: SQL: find gap in sequence 
Sql :: the primary key is selected from the 
Sql :: float in sql 
Sql :: how to filter in sql 
ADD CONTENT
Topic
Content
Source link
Name
1+1 =