is there a way to get the rows with the count of the same table in mysql?

One option uses a subquery:

select id, first_name,
    (select count(*) from mytable t1 where t1.sponsor_id = t.id) sponsored_count
from mytable t

You could also left join an aggregate query:

select t.id, t.first_name, t1.sponsored_count
from mytable t
left join (
    select sponsor_id, count(*) sponsored_count
    from mytable
    group by sponsor_id
) t1 on t1.sponsor_id = t.id

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top