Tuesday, 7 January 2014

Parent child relationship mysql query

Create table like this :-

CREATE TABLE `nodeslist` (
  `NodeID` mediumint(9) NOT NULL AUTO_INCREMENT,
  `NodeTypeID` tinyint(3) unsigned NOT NULL,
  `NodeCode` char(20) NOT NULL,
  `NodeLocationName` char(75) NOT NULL,
  PRIMARY KEY (`NodeID`),
) ;

Here this query to select tree struture data :-

 SELECT
    p.NodeID as parent_id,
    c1.NodeID as child_id_1,
    c1.ParentNode as parent_id_1,
    c2.NodeID as child_id_2,
    c2.ParentNode as parent_id_2,
    c3.NodeID as child_id_3,
    c3.ParentNode as parent_id_3
FROM
    nodeslist p
LEFT JOIN nodeslist c1
    ON c1.ParentNode = p.NodeID
LEFT JOIN nodeslist c2
    ON c2.ParentNode = c1.NodeID
LEFT JOIN nodeslist c3
    ON c3.ParentNode = c2.NodeID
WHERE
    p.ParentNode=0;

Select all child and subchild for particular Parent ID:-

SELECT NodeID,ParentNode,NodeTypeID
FROM nodeslist
WHERE NodeID = 1
OR ParentNode = 1
OR ParentNode IN (SELECT NodeID
    FROM nodeslist
    WHERE ParentNode = 1 OR
    ParentNode IN (SELECT NodeID
    FROM nodeslist
    WHERE ParentNode = 1)

  );

No comments:

Post a Comment