如何查找具有id和父id结构的所有子节点

时间:2018-05-24 10:24:08

标签: php json mysqli

我的广告资料数据是:

  -- ----------------------------
  -- Table structure for abr_cat
  -- ----------------------------
CREATE TABLE `abr_cat` (
 `ID` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(100) NOT NULL,
 `ParentID` int(11) NOT NULL, 
 `status` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of abr_cat
-- ----------------------------
INSERT INTO `abr_cat` VALUES ('22', 'cat 1', '0', '1');
INSERT INTO `abr_cat` VALUES ('23', 'sub cat 1-1', '22', '1');
INSERT INTO `abr_cat` VALUES ('24', 'sub cat 1-2', '22', '1');
INSERT INTO `abr_cat` VALUES ('25', 'sub cat 1-1-1', '23', '1');
INSERT INTO `abr_cat` VALUES ('26', 'cat 2', '0', '1');
INSERT INTO `abr_cat` VALUES ('27', 'sub cat 2-1', '26', '1');
INSERT INTO `abr_cat` VALUES ('28', 'sub cat 1-1-1-1', '25',  '1');
INSERT INTO `abr_cat` VALUES ('29', 'sub cat 1-1-1-1-1', '28', '1');
INSERT INTO `abr_cat` VALUES ('30', 'cat 3', '0', '1');

例如,我想找到所有ID = 22的孩子和这个输出:

[
    {
        "ID": 23,
        "title": "sub cat 1-1",
        "ParentID": 22,
        "status": 1
    },
    {
        "ID": 24,
        "title": "sub cat 1-2",
        "ParentID": 22,
        "status": 1
    },
    {
        "ID": 25,
        "title": "sub cat 1-1-1",
        "ParentID": 23,
        "status": 1
    },
    {
        "ID": 28,
        "title": "sub cat 1-1-1-1",
        "ParentID": 25,
        "status": 1
    },
    {
        "ID": 29,
        "title": "sub cat 1-1-1-1-1",
        "ParentID": 28,
        "status": 1
    }
]

1 个答案:

答案 0 :(得分:0)

尝试此查询并加入将有所帮助:

   SELECT a.title FROM
   `abr_cat`  as a left join `abr_cat` as b 
    on b.`ParentID` = a.`ID` where a.`ParentID` =22

截图: http://prntscr.com/jm06li