Suppose you have a tblRoom and tblUserInfo. Now, you need to select all the rooms regardless of whether the room has user information or not. This calls for a LEFT JOIN which will select everything from the LEFT side (the room side) regardless of the join on the right side. Here is the example.
假如你有兩張表tblRoom(房 間表)和tblUserInfo(住戶表)。
現在你需要檢索出所有房間的信息,而不管這個房間是否有人居住。這就需要進行LEFT JOIN(左外連接),左外連接會檢索出LEFT JOIN左邊表中的所有行,而不管右邊的表是否有匹配項。下面是一個例子:
var list = from r in dc.tblRooms join ui in dc.tblUserInfos on r.UserName equals ui.UserNameinto userrooms from ur in userrooms.DefaultIfEmpty() select new { FirstName = (ur.FirstName == null) ? "N/A" : ur.FirstName, LastName = (ur.LastName == null) ? "N/A" : ur.LastName, RoomName = r.Name };
he anonymous type replaces the "null" FirstName and LastName with "N/A" (not available).
使用"N/A"(不可得)代替 FirstName 和 LastName 值為"null"的情況。
另附:Linq實現多個表 LEFT JOIN 如下
目標SQL語句(多表 LEFT JOIN 查詢)
SELECT id, name, jname, cname FROM userinfo u LEFT JOIN job j on u.job = j.jid LEFT JOIN city c on u.city = c.cid
Linq To Sql 實現三個表 LEFT JOIN 如下:
var list = ( from u in dc.userinfos join j in dc.jobs on u.job equals j.jid into j_join from x in j_join.DefaultIfEmpty() join c in dc.cities on u.city equals c.cid into c_join from v in c_join.DefaultIfEmpty() select new { id = u.id, name = u.name, jname = x.jname, cname = v.cname, /*u1=u,x1=x,v1=v*/ //不要用對象的方式 因為對象可能為null那么對象.屬性就會拋異常 } ).ToList(); for (var i = 0; i < list.Count(); i++) { Console.WriteLine(list[i].name + '\t' + list[i].jname + '\t' + list[i].cname); //字段為null不報異常 //Console.WriteLine(list[i].u1.name+'\t'+list[i].x1.jname+'\t'+list[i].v1.cname+"\r\n"); //對象x1 v1 有可能為null 拋異常 } Console.ReadLine();
3個表 LEFT JOIN 例子:
Emp(員工表)、Dept(部門表)、KqEmp(人員考勤信息表)