use ck2;

create or replace function count_descendants(cid int unsigned) returns int unsigned return (
    with recursive Descendants as (
        select * from Characters where id = cid
        union
        select c.* from Characters as c, Descendants as d
            where d.id = c.mother_id or d.id = c.real_father_id
    ) select count(distinct(id)) from Descendants
    );

select count_descendants(91402);

drop function count_descendants;
