INSERT INTO distri_share_path (ancestor,
anc_name,
anc_nick_name,
anc_phone,
descendant,
desc_name,
desc_nick_name,
desc_phone,
depth, sort)
SELECT ancestor,
anc_name,
anc_nick_name,
anc_phone,
#{newDescendantId},
#{newDescendantName},
#{newDescendantNickName},
#{newDescendantMobile},
depth + 1,
(SELECT IFNULL(MAX(sort), 0) + 1 FROM distri_share_path WHERE ancestor = #{parentId} AND depth = 1)
FROM distri_share_path
WHERE descendant = #{parentId}
UNION ALL
SELECT #{parentId},
#{parentName},
#{parentNickName},
#{parentMobile},
#{newDescendantId},
#{newDescendantName},
#{newDescendantNickName},
#{newDescendantMobile},
1,
(SELECT IFNULL(MAX(sort), 0) + 1 FROM distri_share_path WHERE ancestor = #{parentId} AND depth = 1);
DELETE
FROM distri_share_path
WHERE descendant IN (SELECT descendant
FROM distri_share_path
WHERE ancestor = #{nodeId})
AND ancestor NOT IN (SELECT descendant
FROM distri_share_path
WHERE ancestor = #{nodeId});
INSERT INTO distri_share_path (ancestor, descendant, depth, sort)
SELECT np.ancestor, c.descendant, np.depth + c.depth + 1, 0
FROM distri_share_path AS np
CROSS JOIN (SELECT descendant, depth
FROM distri_share_path
WHERE ancestor = #{nodeId}) AS c
WHERE np.descendant = #{newParentId}
UNION ALL
SELECT #{nodeId} as ancestor, descendant, depth + 1, 0
FROM distri_share_path
WHERE ancestor = #{nodeId};