mysql - Fetch records of parent table depending on count of children -
i have 2 tables, a , b, b has foreign keys a (i.e. a can have 0 or many children in b whereas each b record belongs 1 a record).
now want fetch records a the number of children in b lower x (including zero).
how can achieve comparison of aggregate function?
select a.*, count(b.id) child_cnt left join b on a.id = b.foreign_id group a.id however, cannot add where condition child_cnt of course. pointers how desired result can achieved?
you can use having filter result
select a.*, ifnull(count(b.id), 0) child_cnt left join b on a.id = b.foreign_id group a.id having count(b.id) < x
Comments
Post a Comment