在单个SQL查询和Linq查询中查找多个父项的所有子项

时间:2014-02-07 11:35:57

标签: sql linq entity-framework-4 linq-to-entities self-referencing-table

我需要SELECT使用LINQSQL进行查询,结果如下:

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

我的Table是:

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

3 个答案:

答案 0 :(得分:1)

试试这个SQL查询:

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

答案 1 :(得分:1)

在SQL中,自联接应该这样做:

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

答案 2 :(得分:1)

您可以使用IdParentId自行加入表格。以下代码是LINQ实现此方法:

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();
}

您可以使用Console测试结果:(或者使用Debug.WriteLine()更改结果,以便在无法使用控制台的情况下在输出窗口中查看结果)

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

对于SQL查询,您可以使用:

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