How to write a query to check if a child has any children in a table

痴心易碎 提交于 2019-12-11 04:26:13

问题


I have two tables named User and ParentUser that there is an one to many relation between them and the many side is the ParentUser table.

I wanna write a query to pass a parentId and fetch all of its children and a column name HasChildren to see whether every child has any children or not.

The picture below shows some sample data and needed result:

Tries:

1-By Prdp

SELECT u.*,
       CASE
         WHEN p.ParentId IS NULL THEN 1
         ELSE 0
       END as HasChildren
FROM   [User] u
       LEFT JOIN (select distinct ParentId from ParentUser) p
              ON u.UserId = p.ParentId

All good here but I cant pass a parentId to it.

2- By Juozas

DECLARE @ParentId INT = 2441;

SELECT DISTINCT
     [UserId]       =   [u].[userid]
    ,[HasChildren]  =   CAST(ISNULL([pu].[userid], 0) AS BIT)
    ,[ChildrenId]   =   [pu].[userid]
FROM
    [user]  AS  [u]
OUTER APPLY
    (
        SELECT [userid], [parentid] FROM [ParentUser] WHERE [parentid] = [u].[userid]
    )       AS  [pu]
WHERE
        [pu].[parentid] = @ParentId;

All good again but the field HasChildren's value is always 1.


回答1:


SELECT UserId, HasChildren = CASE WHEN EXISTS(SELECT 1 FROM ParentUser pu2
                                              WHERE pu2.ParentId = pu.UserId)
                             THEN 1 ELSE 0 END
FROM ParentUser pu
WHERE ParentId = @ParentId
ORDER BY UserId


来源:https://stackoverflow.com/questions/41672098/how-to-write-a-query-to-check-if-a-child-has-any-children-in-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!