加入 2 table 并将特定记录置于顶部
joining 2 table and bringing particular record at top
我有 2 个 table。第一个 table 有很多行,但第二个 table 只有一个 1 or 0
记录。如果第二个 table 包含一条记录,那么第一个 table 的记录应该排在最前面。如果第二个 table 不包含任何记录,那么应该显示第一个 table 的所有记录。
首先 table:
DEPT:-
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
第二个table
EMP:-
1000 Shruti 40
例如,如果我加入 table,那么部门 table 的部门号 40 应该排在最前面。我在下面写了查询,它正在工作
select d.deptno,d.dname ,d.loc,e.empno,e.deptno from dept d ,emp e where d.deptno= e.deptno(+) and d.deptno in(select deptno from emp)
UNION ALL
select d.deptno,d.dname ,d.loc,e.empno,e.deptno from dept d ,emp e where d.deptno= e.deptno(+) and d.deptno not in(select deptno from emp);
如果 table emp
没有记录,我如何修改上面的查询,以便显示 dept
table 的所有记录。
我想你想要一个 left join
和一个条件排序:
select d.*, e.empno
from dept d
left join emp e on e.deptno = d.deptno
order by case when e.deptno is not null then 0 else 1 end, d.deptno
根据您的数据,您可以将其简化为:
order by e.deptno, d.deptno
这利用了升序排序将 null
个值放在最后的事实。
我有 2 个 table。第一个 table 有很多行,但第二个 table 只有一个 1 or 0
记录。如果第二个 table 包含一条记录,那么第一个 table 的记录应该排在最前面。如果第二个 table 不包含任何记录,那么应该显示第一个 table 的所有记录。
首先 table:
DEPT:-
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
第二个table
EMP:-
1000 Shruti 40
例如,如果我加入 table,那么部门 table 的部门号 40 应该排在最前面。我在下面写了查询,它正在工作
select d.deptno,d.dname ,d.loc,e.empno,e.deptno from dept d ,emp e where d.deptno= e.deptno(+) and d.deptno in(select deptno from emp)
UNION ALL
select d.deptno,d.dname ,d.loc,e.empno,e.deptno from dept d ,emp e where d.deptno= e.deptno(+) and d.deptno not in(select deptno from emp);
如果 table emp
没有记录,我如何修改上面的查询,以便显示 dept
table 的所有记录。
我想你想要一个 left join
和一个条件排序:
select d.*, e.empno
from dept d
left join emp e on e.deptno = d.deptno
order by case when e.deptno is not null then 0 else 1 end, d.deptno
根据您的数据,您可以将其简化为:
order by e.deptno, d.deptno
这利用了升序排序将 null
个值放在最后的事实。