SELECT @r AS _id , ( SELECT @r : = parent_id FROM department WHERE id = _id ) AS parent_id , @l : = @l + 1 AS lvl ( SELECT @r : = #{id}, @l := 0) vars, department h WHERE @r <> 0 ) T1 JOIN department T2 ON T1 . _id = T2 . id ORDER BY T1 . lvl DESC

查询所有子级

SELECT
			SELECT
				@ids AS _ids,
				( SELECT @ids := GROUP_CONCAT( id ) FROM department WHERE FIND_IN_SET( parent_id, @ids ) ) AS cids,
				@l := @l + 1 AS LEVEL1
				department,
				( SELECT @ids := #{id}, @l := 0 ) b
			WHERE
				@ids IS NOT NULL
			) id,
			department DATA
		WHERE
			FIND_IN_SET( DATA.id, _ids )
		ORDER BY
			LEVEL1
CREATE TABLE `tree_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `parent_id` int(11) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- 插入记录
INSERT INTO `tree_table`(`id`, `pa
	SELECT
		@r AS _id,
		( SELECT @r := department_parent_id FROM department WHERE id = _id ) AS department_parent_id,
		@s := @s + 1 AS sort 
		( SELECT @r := 35, @s := 0 ) temp,
		department 
	WHERE
DROP TABLE IF EXISTS `merchant_region`;
CREATE TABLE `merchant_region`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `parent_id` int(11) NULL DEFAULT NULL,
  `name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMAR
				
比如yjy_content_type表,parent_id为父级id,sort为排序字段,且父级子级都需要根据自己的级别排序查询出来。 思路:在查询的时候先将父级的排序g_max_sort加到子级上(此字段主要是用于父级排序),然后用另一个字段sortg显示是否是同一组(有parent_id就用parent_id的值,否则用自己的id值)。 SELECT a.`id`, a.`parent_id`, a.`sort`, (CASE WHEN a.parent_id!=0 THEN b.so
组织之间存在层级关系,人员可对应多个组织,对应的多个组织也可以存在上下级关系。 查询某个人的组织的时候,需要把这个人对应的所有组织,和对应的每一个组织的所有上级都按序查询出来。 PersonListDto public class PersonListDTO { private Long id; private String personCode; private String name; private String position;