Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.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
在自引用表中获取没有子项且未映射任何父项的所有记录?-SQL_Sql_Sql Server_Database_Oracle - Fatal编程技术网

在自引用表中获取没有子项且未映射任何父项的所有记录?-SQL

在自引用表中获取没有子项且未映射任何父项的所有记录?-SQL,sql,sql-server,database,oracle,Sql,Sql Server,Database,Oracle,我有一个自引用表,其内容如下: 自引用父表 emp_id man_id(FK of emp_id or ParentID) --------------------- 1 (null) 2 (null) 3 (null) 4 2 5 2 6 3 7 3 8 1 9 (null) 10 (null) 11 (null) 帮助我使用以下SQL语句:(没有任何关系

我有一个自引用表,其内容如下: 自引用父表

 emp_id man_id(FK of emp_id or ParentID)
    ---------------------
    1   (null)
    2   (null)
    3   (null)
    4   2
    5   2
    6   3
    7   3
    8   1
    9   (null)
    10  (null)
    11  (null)
帮助我使用以下SQL语句:(没有任何关系的emp_id)

提前感谢

这样试试吧

select e.emp_id from emp e where 
e.man_id is null and e.emp_id 
not in (select distinct man_id from emp where man_id is not null) 
另一个选项是使用
左连接

select e.emp_id from emp e 
left join emp e2 ON e.emp_id = e2.man_id 
where e2.man_id is null and e.man_id is null

您可以使用
LEFT JOIN
查找未被引用为
man\u id

   select e.emp_id, e.man_id from emp e
   left outer join emp e1 on e1.man_id = e.emp_id
   where e1.emp_id is null
如果您还希望约束结果,使emp_id没有man_id,则可以执行以下操作:

   select e.emp_id, e.man_id from emp e
   left outer join emp e1 on e1.man_id = e.emp_id
   where e1.emp_id is null and e.man_id is null

您可以选择两条需要注意的规则-
1.如果
manu id
列中存在
emp\u id
,则应将其从结果中排除
2.如果一个
emp\u id
映射了一些
man\u id
,则应将其从结果中排除

这可以使用self上的左连接来完成

SELECT A.EMP_ID
FROM
EMP A LEFT JOIN EMP B
ON A.EMP_ID = B.MAN_ID
WHERE A.MAN_ID IS NULL AND B.MAN_ID IS NULL;

第一个
WHERE
条件将处理规则1,第二个
WHERE
条件将处理规则2。

Oracle或SQL Server?这是两个非常不同的DBMS
SELECT A.EMP_ID
FROM
EMP A LEFT JOIN EMP B
ON A.EMP_ID = B.MAN_ID
WHERE A.MAN_ID IS NULL AND B.MAN_ID IS NULL;