Mysql树形结构表操作

sql语句:

# 查询所有叶子节点
select id from t_area where id not in (select p_id from t_area);
-- select areaname from sm_area where id not in (select parent_id from sm_area);

# 查询节点所有父节点
select
	@v as _id,
	(select @v := p_id from t_area where id = _id) as _pid,
	(select @l := @l + 1) as _lvl
from
	(select @v := 8, @l := -1) vars,
	t_area
where
	@v != -1;

# 查询所有子节点
/*SELECT 
areaname
from(
SELECT
	id,
	areaname,
	IF( find_in_set( parent_id, @pids ) > 0, @pids := concat( @pids, ',', id ), 0 ) AS ischild 
FROM
	sm_area,
	( SELECT @pids := 320000 ) t2) t3 WHERE ischild != 0;*/
select
	id
from(
	select 
		id,
		if(find_in_set(p_id, @pids) > 0, @pids := concat( @pids, ',', id), 0) as ischild
	from
		t_area,
		(select @pids := 1) T2
) T1
where ischild != 0;
	

表结构:

-- ----------------------------
-- Table structure for t_area
-- ----------------------------
DROP TABLE IF EXISTS `t_area`;
CREATE TABLE `t_area`  (
  `id` int(11) NOT NULL,
  `p_id` int(11) NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of t_area
-- ----------------------------
INSERT INTO `t_area` VALUES (0, -1);
INSERT INTO `t_area` VALUES (1, 0);
INSERT INTO `t_area` VALUES (2, 0);
INSERT INTO `t_area` VALUES (3, 0);
INSERT INTO `t_area` VALUES (4, 1);
INSERT INTO `t_area` VALUES (5, 1);
INSERT INTO `t_area` VALUES (6, 2);
INSERT INTO `t_area` VALUES (7, 3);
INSERT INTO `t_area` VALUES (8, 4);
INSERT INTO `t_area` VALUES (9, 8);
INSERT INTO `t_area` VALUES (10, 9);

SET FOREIGN_KEY_CHECKS = 1;

树形图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值