递归查询

表:test id(BIGINT) parent_id(BIGINT) data(INT)

create function getSumByParentId(parentId BIGINT) returns int
begin
declare result int;
with temp as(
select * from test where id = parentId
union all select test.* from temp, test where temp.Id = test.parent_id
);
select sum(data) from temp into result;
return result;
end;

select id,getSumByParentId(id) from test;

原文地址:https://www.cnblogs.com/xiaohan970121/p/11749545.html