简体   繁体   中英

get records whose child count is less than 2

I am working on tree based architecure. There is one table called user. I have providing schema of the table as follows:

    CREATE TABLE `user5` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `parent_id` int(11) NOT NULL,
  `position` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `user5`
--

INSERT INTO `user5` (`id`, `name`, `parent_id`, `position`) VALUES
(1, 'test1', 0, 'NULL'),
(2, 'test2', 1, 'left'),
(3, 'test3', 1, 'right'),
(4, 'test4', 2, 'left'),
(5, 'test5', 2, 'right'),
(6, 'test6', 3, 'left'),
(7, 'test7', 3, 'right'),
(8, 'test8', 6, 'left'),
(9, 'test9', 6, 'right'),
(10, 'test10', 7, 'left');

I am passing one id as input to my foloowing query which returns all child level nodes.

SELECT
     GROUP_CONCAT(lv SEPARATOR ',') as team_members
 FROM
     (
     SELECT
         @pv:=(
             SELECT
                 GROUP_CONCAT(id SEPARATOR ',')
             FROM
                 user5
             WHERE
                 FIND_IN_SET(parent_id, @pv)
         ) AS lv
     FROM
         user5
     JOIN
         (SELECT @pv:=3)tmp
     WHERE
         parent_id IN (@pv)
                       ) a

if I am passing 3 as input to above query then will return me following result.

6,7,8,9,10

I am appending 3 as first element in above result.

after appending : 3,6,7,8,9,10

So Now I want those ids which have less than 2 childs either 1 or 0. So my exprected result should be as follows :

id  Childcount
7   1
8   0
9   0
10  0

So now I need to return only those ids which has less than 2 childs. It means it should return those id, count(count of child) which have either 0 or 1 child only. So how can we do this. Please help me in this. Thanks in advance

I got the answer as follows :

SELECT 
    a.id, 
    a.parent_id as ParentID, 
    b.TotalCout 
FROM 
    user5 a 
INNER JOIN 
    ( 
    SELECT 
        parent_id, 
        COUNT(1) as TotalCout 
    FROM 
        user5 
    WHERE 
        parent_id <> id 
    GROUP BY 
        parent_id 
    ) b 
ON 
    a.id = b.parent_id 
AND 
    b.TotalCout < 2 
AND 
    a.id IN(3,6,7,8,9,10)
UNION ALL
SELECT
    yt1.id,
    yt1.parent_id as ParentID,
    0 as TotalCout

FROM 
    user5 yt1
LEFT JOIN 
    user5 yt2
ON 
    yt1.id = yt2.parent_id
WHERE 
    yt2.id is null 
AND 
    yt1.id IN(3,6,7,8,9,10)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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