0

我需要使用SELECT查询LINQ并且SQL结果为:

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
4

3 回答 3

1

您可以使用和列自连接表。以下代码是这种方法的实现:IdParentIdLINQ

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
于 2014-02-07T12:11:45.447 回答
1

试试这个SQL查询:

select parentid, country, state, childID 
from tablename 
where parentid IN (1,5)
于 2014-02-07T11:46:14.763 回答
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
于 2014-02-07T12:07:54.800 回答