linq2sql join选择不在另一个表中的数据

时间:2012-07-25 02:24:23

标签: c# sql winforms c#-4.0 linq-to-sql

请不要使用lamba回复。我找到了类似的线程,但仍然需要帮助。

我正在尝试显示employees表中不是当前所选经理员工的姓名。

我的两个sql表的结构如下,但这是假数据

Employees:   
           pk      name     
           1      bob
           2      sam
           3      greg
           4      kip
           5      jill
           6      kelly
           7      chris


ExpenseTeamMembers: 

           pk      expMgrPk     empPk     
           1         7          2
           2         7          5
           3         7          1
           4         3          6
           5         3          4

因此,如果当前选择的(mgr变量)为3,我想获取employees表中除了6,4之外的所有empPks的名称。(kelly,kip)现在unselectedEmps = sam,jill,bob而不是employees表中的所有其他5个名称。

var unselectedEmps = (from u in db.employees
                      join o in db.expenseTeamMembers on u.pk equals o.empPk
                      where o.expMgrPk != mgr 
                      select u.name).ToList();

                lstAvailable.DataSource = unselectedEmps;

3 个答案:

答案 0 :(得分:1)

问题在于,当您实际需要左外连接

时,您正在进行内连接

请参阅this SO question

答案 1 :(得分:1)

经过我们的扩展讨论,我认为你想要的是这个。

from u in db.Employees
where !(from e in db.ExpenseTeamMembers
        where e.expMgrPk == selectedMgr.pk
        select e.empPk).Contains(u.pk)
select u.Name

答案 2 :(得分:1)

我尝试了以下内容,它提供了正确的输出。请试一试:

List<Employees> emps = new List<Employees>();
        emps.Add(new Employees { PK = 1, Name = "bob" });
        emps.Add(new Employees { PK = 2, Name = "sam" });
        emps.Add(new Employees { PK = 3, Name = "greg" });
        emps.Add(new Employees { PK = 4, Name = "kip" });
        emps.Add(new Employees { PK = 5, Name = "jill" });
        emps.Add(new Employees { PK = 6, Name = "kelly" });
        emps.Add(new Employees { PK = 7, Name = "chris" });

        List<ExpenseTeamMembers> etm = new List<ExpenseTeamMembers>();
        etm.Add(new ExpenseTeamMembers { empPK = 2, ExpMgrPK = 7, PK = 1 });
        etm.Add(new ExpenseTeamMembers { empPK = 5, ExpMgrPK = 7, PK = 2 });
        etm.Add(new ExpenseTeamMembers { empPK = 1, ExpMgrPK = 7, PK = 3 });
        etm.Add(new ExpenseTeamMembers { empPK = 6, ExpMgrPK = 3, PK = 4 });
        etm.Add(new ExpenseTeamMembers { empPK = 4, ExpMgrPK = 3, PK = 5 });

        var query = from t in
                        (
                            from emp in emps
                            join o in etm on emp.PK equals o.empPK into j
                            from k in j.DefaultIfEmpty()
                            select new { Name = k == null ? string.Empty : emp.Name })
                    where t.Name != string.Empty
                    select t.Name;