0

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

Thomas G
  • 9,886
  • 7
  • 28
  • 41
Yogesh k
  • 352
  • 1
  • 7
  • 22
  • 1
    "I am passing one id as input to my another query which returns all child level nodes including that node." - Please post that query. – Paul Spiegel Jul 05 '18 at 20:07
  • Please look at this [question](https://stackoverflow.com/q/4048151/5962802) and specifically at this [answer](https://stackoverflow.com/a/38701519/5962802) – IVO GELOV Jul 06 '18 at 08:33
  • i have mentioned that I want id's having less than 2 child. – Yogesh k Jul 06 '18 at 08:59

1 Answers1

0

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)
Yogesh k
  • 352
  • 1
  • 7
  • 22