左外連接會檢索出LEFT JOIN左表中的所有行,而不管右表是否有匹配項。
今天的一個項目中,需要將classlist表與其他3張表進行連接查詢,且classlist表中某列為空的數據也需要查詢出來,這就需要進行LEFT JOIN(左外連接查詢),且項目使用的是Entity Framework框架,因此,可以使用Linq語句進行左外連接查詢。
通過左連接4張表(klc_classlist、klc_object 、klc_student 、klc_license )進行查詢,語句如下:
// linq語句多表聯合查詢
var classlist = from a in dc.klc_classlist
join b in dc.klc_object on a.object_id equals b.id into result1
from ab in result1.DefaultIfEmpty()
join c in dc.klc_student on a.student_id equals c.id into result2
from abc in result2.DefaultIfEmpty()
join d in dc.klc_license on abc.license_id equals d.id into result3
from abcd in result3.DefaultIfEmpty()
where a.order_list.Contains(stu_id_str) && (a.student_id == stu_id || a.student_id == null)
select new
{
id = a.id,
date = a.date,
start_time = a.start_time,
end_time = a.end_time,
duration = a.duration,
object_name = ab.name,
student_name = abc.name,
status = a.status
};
