我需要显示父表中来自sql的记录,这些记录的子记录少于4(根本没有子记录也可以),需要SQL查询。
答案 0 :(得分:1)
以下是查询:
SELECT
pt.id, pt.somefield, COUNT(pt.id) as c
FROM
parenttable pt
LEFT OUTER JOIN
chiledtable ct
ON
ct.parenttable_id = pt.id
GROUP BY
pt.id
HAVING
c <= 4
答案 1 :(得分:0)
您可以使用子查询来计算子行数:
select *
from ParentTable as p
left join
(
select parentid
, count(*) as cnt
from ChildTable
group by
parentid
) as c
on c.parentid = p.id
where c.cnt <= 3