Sajith
Sajith

Reputation: 856

Finding all children for multiple parents in single SQL query and Linq query

I need to SELECT query using LINQ and also SQL resulting as:

ParentId   Country   State         ChildId
 1         India     kerala           2
 1         India     TamilNamdu       3
 5         Pakistan  Kasagithan1      6
 5         Pakistan  Kasg2            7

And my Table is:

Id  ParentId Country        State
1   0        India          NULL
2   1        NULL           Kerala
3   1        NULL           TamilNamdu
4   1        NULL           Karnadaka
5   0        Pakisthan      NULL
6   5        NULL           Kasagithan
7   5        NULL           Kasg2
8   5        NULL           Afganistha
9   0        China          NULL
10  9        NULL           Hwuesang1
11  9        NULL           sate1
12  9        NULL           sate2

Upvotes: 0

Views: 1050

Answers (3)

Yuvi
Yuvi

Reputation: 185

Try this SQL query:

select parentid, country, state, childID 
from tablename 
where parentid IN (1,5)

Upvotes: 1

Saro Taşciyan
Saro Taşciyan

Reputation: 5236

You can self-join the table using Id and ParentId columns. The following code is LINQ implementation of this approach:

using (YourEntity yourEntity = new YourEntity())
{
    var result =
    (
        from state in yourEntity.YourTableName
        from country in yourEntity.YourTableName
        where state.ParentId != 0 && state.ParentId == country.Id
        select new { ParentId = state.ParentId, Country = country.Country, State = state.State, ChildId = state.Id }
    ).ToList();
}

You can test the result using Console: (or change it with Debug.WriteLine() to see results in output window if you can't use console)

foreach (var item in result)
{
    Console.WriteLine("{0} {1} {2} {3}", item.ParentId, item.Country, item.State, item.ChildId);
}

And for SQL Query you can use:

SELECT state.ParentId, country.Country, state.State, state.Id As 'ChildId'
FROM YourTableName As state INNER JOIN YourTableName AS country
    ON state.ParentId <> 0 AND state.ParentId = country.Id

Upvotes: 1

Fredrik Ljung
Fredrik Ljung

Reputation: 1475

In SQL a self join should do it:

SELECT P.Id AS ParentId, P.Country, C.State, C.Id AS ChildId
FROM table AS P
JOIN table as C ON C.ParentId = P.Id AND C.ParentId <> 0
WHERE P.State IS NULL

Upvotes: 1

Related Questions