How to implement SELECT "hasChildren" statement in SQL?

Let's say I have the following table:

ID | parentID | MoreStuff
1  | -1       |  ...
2  |  1       |  ...
3  |  1       |  ...
4  |  2       |  ...
5  |  1       |  ...

How can I generate a SQL SELECT statement to find out if a particular row has children? In other words, I want to know if ID 1 has children, which in this case have 3.

I am not sure how to create an SQL statement:

SELECT ID, hasChildren FROM myTable;

What will be replaced with hasChildren in the SQL SELECT statement above?

+3
source share
5 answers

No group version:

SELECT MyTable.Id, CASE WHEN EXISTS 
    (SELECT TOP 1 1  --you can actually select anything you want here
     FROM MyTable MyTableCheck 
     WHERE MyTableCheck.ParentId = MyTable.Id
    ) THEN 1 ELSE 0 END AS HasRows
FROM MyTable
+15
source

Join the table to find out if she has children:

SELECT 
    parent.id as ID
,   case when count(child.id) > 0 then 1 else 0 end as hasChildren 
FROM       myTable parent
LEFT JOIN  myTable child
ON         child.parentID = parent.ID
GROUP BY   parent.id
+12
source

, - .

SELECT count(*) FROM myTable where parentID = 1;
+2

, . , , .

Sub Query , , ID .

, "haschildren", "" . , . :

SELECT * FROM table WHERE haschildren IS NOT NULL
+2

, , "haschildren", (. GateKiller). , .. , , . , , .

+1

Source: https://habr.com/ru/post/1724039/


All Articles