如题  请教mysql 的大神们,怎么让子父级关系一对一关联,测试数据如下
CREATE TABLE a (
`id`  int(100) NOT NULL ,
`name`  varchar(20) NULL ,
`pid`  int NULL 
);INSERT into a VALUE (1,'父类1',null);
INSERT into a VALUE (2,'父类2',null);
INSERT into a VALUE (3,'子类1',1);
INSERT into a VALUE (4,'子类2',1);
INSERT into a VALUE (5,'子类3',2);
INSERT into a VALUE (6,'子类4',3);怎么得到如下结果id1 name1 pid id2 name2 pid2
1   父类1   null   3   子类1    1
1   父类1   null   4   子类2    1
1   父类1   null   6   子类4    3
2   父类2   null   5   子类3    2就是父级和所拥有的子级形成直接的一对一关联或者得到第二种结果id1 name1 pid id2 name2 pid2
1   父类1  null    6   子类4    3
1   父类1  null    4   子类2    1
2   父类2  null    5   子类3    2最上层的父级和最末的子级形成一对一关联。

解决方案 »

  1.   

    DROP TABLE IF EXISTS `mytest`;
    CREATE TABLE `mytest` (
      `id` int(11) DEFAULT NULL,
      `socre` int(11) DEFAULT NULL,
      `group` varchar(255) DEFAULT NULL,
      `pid` int(11) DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ----------------------------
    -- Records of mytest
    -- ----------------------------
    INSERT INTO `mytest` VALUES ('1', '30', 'u', null);
    INSERT INTO `mytest` VALUES ('2', '5', 'u1', '1');
    INSERT INTO `mytest` VALUES ('3', '6', 'u2', '1');
    INSERT INTO `mytest` VALUES ('4', '5', 'a', null);
    INSERT INTO `mytest` VALUES ('5', '4', 'a1', '4');
    INSERT INTO `mytest` VALUES ('6', '7', 'a3', '4');
    INSERT INTO `mytest` VALUES ('7', '6', 'a6', '4');
    INSERT INTO `mytest` VALUES ('8', '9', 'c', null);
    select * from mytest;#select `group` from mytest  where  pid is null GROUP BY `group`;
    select `group` from mytest  where  pid is null GROUP BY `group`;
    select aa.`group`,sum(t.socre) from mytest t , (select `group` from mytest  where  pid is null GROUP BY `group`) aa where t.`group` like CONCAT(aa.`group`,'%') group by aa.`group` ;select aa.`group`,t.`group` from mytest t , (select `group` from mytest  where  pid is null GROUP BY `group`) aa where t.`group` like CONCAT(aa.`group`,'%') 
      

  2.   

    递归查询,这种如果层级少还ok,如果层级很深,几乎没有好办法,
    你可以百度一下 左右树,或者参考:
    https://www.cnblogs.com/M-D-Luffy/p/4712846.html
    这种存储结构,对于读多 写少的设计还有比较高效的