简体   繁体   中英

How are these two Oracle queries different?

How oracle executes these two queries with different results

1.

SELECT e.ename,
       m.ename
FROM   emp e,
       emp m
WHERE  e.empno = m.mgr;

2.

SELECT e.ename,
       m.ename
FROM   emp e,
       emp m
WHERE  m.empno = e.mgr; /*<-- Different*/

Not getting the clear result...

Thank you, all of you in advance .

The first query shows managers and their employees, for example BLAKE is the manager for 5 staff. The second shows employees and their managers, so BLAKE appears five times in the second column.

I think they could be written more clearly, as:

-- Managers and their employees:
select m.ename as manager
     , e.ename as employee
from   emp m
       join emp e on e.mgr = m.empno
order by 1,2;

MANAGER    EMPLOYEE
---------- ----------
BLAKE      ALLEN
BLAKE      JAMES
BLAKE      MARTIN
BLAKE      TURNER
BLAKE      WARD
CLARK      MILLER
FORD       SMITH
JONES      FORD
JONES      SCOTT
KING       BLAKE
KING       CLARK
KING       JONES
SCOTT      ADAMS

13 rows selected

-- Employees and their managers:
select e.ename as employee
     , m.ename as manager
from   emp e
       join emp m on m.empno = e.mgr
order by 1,2;

EMPLOYEE   MANAGER
---------- ----------
ADAMS      SCOTT
ALLEN      BLAKE
BLAKE      KING
CLARK      KING
FORD       JONES
JAMES      BLAKE
JONES      KING
MARTIN     BLAKE
MILLER     CLARK
SCOTT      JONES
SMITH      FORD
TURNER     BLAKE
WARD       BLAKE

13 rows selected

Those are two different queries:

  • The first one lists the employees (left) with their managers (right).

  • The second one lists the managers (left) with their employees (right).

You need to decide which one you want.

Also, you should really use the JOIN keyword when joining two tables (it's not the 90s anymore). Your first query will look like:

SELECT e.ename,
       m.ename
  FROM emp e
  JOIN emp m on e.empno = m.mgr;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM