简体   繁体   English

显示父表中子记录少于4个的记录

[英]Show Records from parent table that have child records less than 4

我需要显示来自父表的sql记录,该记录的子记录少于4个(根本没有子记录也可以),请使用SQL查询。

Here's the query: 这是查询:

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

You could use a subquery to calculate the number of child rows: 您可以使用子查询来计算子行的数量:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM