I need to display records from my sql from the parent table that have child records less than 4 or no child records, Need SQL query please.
More Clarification:
- having no child records of a parent at all is also fine, all parent records should display
- If the parent record has child records between 1 and 3, should display
- if the parent record has exactly 4 child records, it shouldn’t be displayed.
Schema (an employee can’t have more than 4 donations)
client (client_id, email)
employee (employee_id, name)
donation (donation_id, employee_id, client_id)
SQL I’ve tried.
SELECT * FROM employee left join
(SELECT donation_id, employee_id, client_id, count(employee_id) as count from donation GROUP BY employee_id HAVING count <= 4) as d
ON employee.employee_id = d.employee_id
You can just join the tables, group by employee and filter the groups for those with less than 4 records: