我继承了一个设计不完全优化的数据库,并且我需要操作一些数据。让我对我必须做的事情给出一个更常见的类比:
假设我们有一个Student
桌子,一个StudentClass
记录他参加的所有课程的表格,以及StudentTeacher
表存储了所有教过该学生的老师。是的,我知道这是一个愚蠢的设计,将教师存储在班级表上会更有意义 - 但这就是我们正在研究的。
我现在想要清理数据,我想找到所有学生有老师但没有班级,或者有班级但没有老师的地方。 SQL 如下:
select *
from StudentClass sc
full outer join StudentTeacher st on st.StudentID = sc.StudentID
where st.id is null or sc.id is null
在 Linq 中如何做到这一点?
我想我在这里得到了答案,它并不像我希望的那么优雅,但它应该可以解决问题:
var studentIDs = StudentClasses.Select(sc => sc.StudentID)
.Union(StudentTeachers.Select(st => st.StudentID);
//.Distinct(); -- Distinct not necessary after Union
var q =
from id in studentIDs
join sc in StudentClasses on id equals sc.StudentID into jsc
from sc in jsc.DefaultIfEmpty()
join st in StudentTeachers on id equals st.StudentID into jst
from st in jst.DefaultIfEmpty()
where st == null ^ sc == null
select new { sc, st };
您可能可以将这两个语句压缩为一个,但我认为您会牺牲代码的清晰度。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)