Using SQL, how do you find the child number in a table from two columns where they are parent-child relationships?

Viewed 29

enter image description here

From this table, after querying I want to get the child column that shows the number of the child for each id.

I want:

enter image description here

1 Answers

A scalar subquery will produce the data you want. For example:

select
  t.*,
  (select count(*) from t b where b.parent_id = t.id) as child
from t
Related