I have the following query that I do not understand how it works, especially the subquery that returns the minimum ID without grouping.
WITH RECURSIVE t(id, user_id, name) AS (
select min(id) - 1, user_id, null as name from attempts group by user_id
UNION ALL
select * from (
with t_inner as (select * from t),
next_id as (
select min(attempts.id) as id
from attempts
left join t_inner using(name)
where attempts.id > (select min(id) id from t_inner)
and t_inner.name is null
)
select next_id.id, t_inner.user_id, coalesce(attempts.name, t_inner.name) as name
from t_inner cross join next_id left join attempts
on (attempts.id = next_id.id)
and (attempts.user_id = t_inner.user_id)
where next_id.id is not null
) as t2
)
select t.user_id, t.name
from t natural join (select user_id, max(id) as id from t group by user_id) mas_id
order by user_id, id
;
Shouldn't this subquery always return the same number regardless of the iteration step?
(select min(id) id from t_inner)