1. 程式人生 > >SQL 和LINQ 左連線 , 右連線, 內連線 語法對照

SQL 和LINQ 左連線 , 右連線, 內連線 語法對照

LINQ 語法

TSQL

左聯接

 var equipmentType = from a in ctx.TB_EquipmentType
                                join b in ctx.TB_User on a.CreatedBy equals b.Id into JoinedTable1
                                join b in ctx.TB_User on a.LastModifiedBy equals b.Id into JoinedTable2
                               
                                from c in JoinedTable1.DefaultIfEmpty()
                                from d in JoinedTable2.DefaultIfEmpty()
                                orderby a.Code ascending, a.Name ascending
                                select new
                                {
                                    Id = a.Id,
                                    Code = a.Code,
                                    Name = a.Name,
                                    Remark = a.Remark,
                                    CreatedTime = a.CreatedTime.ToString(),
                                    CreatedBy = c != null ? c.Name : null,
                                    LastModifiedTime = a.LastModifiedTime,
                                    LastModifiedBy = d != null ? d.Name : null,
                                };

左聯接

SELECT a.Id
      ,a.Code
      ,a.Name
      ,a.Remark
      ,a.CreatedTime
      ,b.Name     
      ,a.LastModifiedTime
      ,c.Name
  FROM TB_EquipmentType as a
  left join TB_User as b on a.CreatedBy = b.Id
  left join TB_User as c on a.LastModifiedBy = c.Id
 
GO

內聯接

 var equipmentType = from a in ctx.TB_EquipmentType
                                join b in ctx.TB_User on a.CreatedBy equals b.Id into JoinedTable1
                                join b in ctx.TB_User on a.LastModifiedBy equals b.Id into JoinedTable2
                               
                                from c in JoinedTable1.DefaultIfEmpty()
                                from d in JoinedTable2.DefaultIfEmpty()
                                orderby a.Code ascending, a.Name ascending
                                select new
                                {
                                    Id = a.Id,
                                    Code = a.Code,
                                    Name = a.Name,
                                    Remark = a.Remark,
                                    CreatedTime = a.CreatedTime.ToString(),
                                    CreatedBy = c != null ? c.Name : null,
                                    LastModifiedTime = a.LastModifiedTime,
                                    LastModifiedBy = d != null ? d.Name : null,
                                };

SELECT a.Id
      ,a.Code
      ,a.Name
      ,a.Remark
      ,a.CreatedTime
      ,b.Name     
      ,a.LastModifiedTime
      ,c.Name
  FROM TB_EquipmentType as a
   join TB_User as b on a.CreatedBy = b.Id
   join TB_User as c on a.LastModifiedBy = c.Id
 
GO