【问题标题】:Finding all children for multiple parents in single SQL query and Linq query在单个 SQL 查询和 Linq 查询中查找多个父母的所有孩子
【发布时间】:2014-02-07 11:35:57
【问题描述】:

我需要使用LINQSQL 查询SELECT,结果为:

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

【问题讨论】:

  • 我建议你改变你的设计。您可以假设每个CountryState 都是一个实体(表)
  • 我使用的父子表是单表
  • 嗯,是的,但是除了带来的麻烦,还有什么好处呢?

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


【解决方案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

【讨论】:

  • @Federik,谢谢我已经测试过了,我在 sql 中得到了结果
【解决方案2】:

您可以使用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

【讨论】:

  • @Sajith 希望你会(:
【解决方案3】:

试试这个SQL查询:

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

【讨论】:

  • 它将检索 ID 为 5 和 1 的所有行。
  • -1: it will retrieve all the rows that has ID 5 and 1 应该是 ID 1 to 5 (between 1 to 5) 以防万一不是问题的正确答案。问题是关于不过滤 ID 的国家与国家的关联
  • @Yuvi 不客气,但尽管它现在已得到纠正,但它仍然没有给出问题的答案。结果将是带有Country 字段NULL印度和巴基斯坦各州
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多