Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
3个表的Sql查询检查表中的任何一个_Sql_Sql Server_Sql Server 2008 - Fatal编程技术网

3个表的Sql查询检查表中的任何一个

3个表的Sql查询检查表中的任何一个,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我有三张桌子 1:员工 2:部门 3:专家 我想要属于CmpId=1的专家 雇员: id CmpId 1 2 2 1 3 1 系 id CmpId 1 1 2 2 3 2 专家们: id EmployeeId DepartmentId 1 1 2 2 2 null 3 null 1 4 2 1 5 null null 把三张表连

我有三张桌子 1:员工 2:部门 3:专家

我想要属于CmpId=1的专家

雇员:

id  CmpId 
1   2   
2   1   
3   1   

id  CmpId 
1   1   
2   2   
3   2
专家们:

id  EmployeeId DepartmentId 
1   1          2
2   2          null
3   null       1
4   2          1
5   null       null

把三张表连在一起

如果两者都需要CmpId=1(这在示例数据中不返回任何内容,但假设它是一个更大的数据集)

如果它们需要在以下任意一种情况下为CmpId=1

SELECT e.id, e.EmployeeId, e.DepartmentId
FROM Experts e
FULL OUTER JOIN Department d ON e.DepartmentId = d.id
FULL OUTER JOIN Employee em ON e.EmployeeId = em.id
WHERE d.CmpId = 1 OR em.CmpId = 1

我猜
expert
表中的
NULL
表示某个人是所有部门的专家。如果是:

select e.employeeid
from experts e join
     departments d
     on e.departmentid = d.id or e.departmentid is null;

如果我正确理解了这个问题,那么基于样本数据的期望结果应该是专家ID的2、3和4

专家ID 2的员工ID为2,其CmpID为1。 专家ID 3的部门ID为1,其CmpID为1。 专家ID 4的员工ID为2,CmpID为1,部门ID为1,CmpID为1

如果这实际上是所需的结果集,我将编写以下查询

SELECT ex.id, ex.EmployeeID, ex.DepartmentID
  FROM @Experts ex
  LEFT JOIN @Department dep
    ON ex.DepartmentID = dep.id
  LEFT JOIN @Employee emp
    ON ex.EmployeeID = emp.id
 WHERE dep.CmpID = 1 OR emp.CmpID = 1
这将产生以下结果

id  EmployeeID  DepartmentID
2   2           NULL
3   NULL        1
4   2           1

您使用哪种数据库管理系统?mysql/sql server和postgresql非常不同。您的示例数据的结果是什么?我们需要使用哪个CmpId?@Jens:使用sql server。我知道所有查询都是不同的,但查询可以转换为任何查询。Gordon Linoff:结果将是专家ID 2,3,4纳沃特辛格:首先,我必须考虑雇员,如果它是空的,那么我只需要考虑部门认为你没有得到我的问题。您正在进行内部联接,如果某个expert.deptId包含null,则联接将给出null@HemantMalpote那就用全外型吧。最新答案
id  EmployeeID  DepartmentID
2   2           NULL
3   NULL        1
4   2           1