在LINQ / SQL中连接表

时间:2009-08-24 18:25:40

标签: sql linq linq-to-sql

我有一组行,每行包含productid,unitid,countryid 我需要在相应的表格(产品,单位,国家/地区)中找到每一行的详细信息

for product - select product name, updatedby  
for unitid  - select unit name , updatedby  
for countryid - select countryname, uploadby  

并返回格式相同的行

Id = product id or unitid or countryid
name = proudct name or unit name or countryname
modified = product updatedby or unit updated by or country uploadby

所以,总结一下 -

 1. For a Collection of rows
    a. use the id to get the extra details from the respective table
    b. return the same type of collection for the results
 2. do step 1 for 
    2.a For RegularToys (Run this logic on TableBigA)
    2.b For CustomToys(Run this logic on TableB)
 3. Return all the rows 
    by adding 2.a and 2.b

如何为此编写sql / linq查询?感谢

2 个答案:

答案 0 :(得分:0)

没有任何进一步的细节我不能更具体地说明下面的情况,但我认为你要求这些方面的东西。我假设您的Id是int(但如果没有,这可以很容易地改变),并且您已经拥有了所描述的表的实体数据模型。

  1. 为您的公共数据创建一个类:
  2. class RowDetail
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Modified { get; set; }
    }
    

    1. 将每个子表中的信息拉出到新记录中:
    2. IEnumerable<RowDetail> products =
          from p in db.Products
          where <<CONDITION>>
          select
              new RowDetail()
              {
                  Id = p.ProductId,
                  Name = p.ProductName,
                  Modified = p.UpdatedBy
              };
      
      IEnumerable<RowDetail> units =
          from u in db.Units
          where <<CONDITION>>
          select
              new RowDetail()
              {
                  Id = u.UnitId,
                  Name = u.UnitName,
                  Modified = u.UpdatedBy
              };
      
      IEnumerable<RowDetail> countries =
          from c in db.Countries
          where <<CONDITION>>
          select
              new RowDetail()
              {
                  Id = c.CountryId,
                  Name = c.CountryName,
                  Modified = c.UploadBy
              };
      

      1. 最后将所有记录集中在一个集合中:
      2. IEnumerable<RowDetail> results = products.Union(units).Union(countries);
        

        我不确定这是否正是您所寻找的,如果需要进一步的帮助,请随时提供反馈和/或更多详细信息。

答案 1 :(得分:0)

如果我理解正确,您希望使用给定的ID来查找产品,单位或国家,但您不确定哪个。如果是这种情况,那么您可以构建这样的延迟查询来查找给定的实体:

var prod = from p in db.Products
           where p.ProductId = id
           select new { Id = p.ProductId, Name = p.ProductName, Modified = p.UpdatedBy };

var unit = from u in db.Units
           where p.UnitId = id
           select new { Id = u.UnitId, Name = u.UnitName, Modified = p.UpdatedBy };

var ctry = from c in db.Countries
           where c.CountryId = id
           select new { Id = c.CountryId, Name = c.CountryName, Modified = c.UploadBy };

然后执行查询,直到找到匹配的实体(??为null-coalesce运算符,如果左侧结果为null则返回正确的值。)

var res = prod.SingleOrDefault() ??
          unit.SingleOrDefault() ??
          ctry.SingleOrDefault() ??
          new { Id = id, Name = null, Modifed = null };
相关问题