mysql 子父级关联关系查询怎么让父级和所有子级一对一关联起来

ou明 2018-03-28 10:16:44
如题 请教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

最上层的父级和最末的子级形成一对一关联。
...全文
1265 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
游北亮 2018-03-30
  • 打赏
  • 举报
回复
递归查询,这种如果层级少还ok,如果层级很深,几乎没有好办法, 你可以百度一下 左右树,或者参考: https://www.cnblogs.com/M-D-Luffy/p/4712846.html 这种存储结构,对于读多 写少的设计还有比较高效的
ou明 2018-03-30
  • 打赏
  • 举报
回复
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`,'%')
ou明 2018-03-29
  • 打赏
  • 举报
回复
来个大神帮忙下啊

56,914

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧