oracle 如何在连接两个表后才从第一个表中获取数据

hkmswyz6  于 2023-10-16  发布在  Oracle
关注(0)|答案(1)|浏览(117)

我们有两张table。第一个表是员工,第二个表是书籍。

CREATE TABLE  EMPLOYEE
   (    "EMPLOYEE_ID" NUMBER(19,0) not null,
    "NAME" VARCHAR2(256),
     CONSTRAINT "ID_PK" PRIMARY KEY ("EMPLOYEE_ID") ENABLE
   );
   
   CREATE TABLE  BOOKS
   (    "ID" VARCHAR2(32) NOT NULL ENABLE,
    "BOOKNAME" VARCHAR2(256),
  "EMP_ID" NUMBER(19,0) not null,
     CONSTRAINT "BOOK_ID_PK" PRIMARY KEY ("ID") ENABLE,
     CONSTRAINT "EMP_FK1" FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE
   );
insert into employee  values (1, 'James');
insert into employee  values (2, 'John');

insert into BOOKS  values (1, 'JAVA', 1);
insert into BOOKS  values (2, 'CProgramming', 1);
insert into BOOKS  values (3, 'JSP', 1);
insert into BOOKS  values (4, 'Accountancy', 2);
insert into BOOKS  values (5, 'History', 2);
insert into BOOKS  values (6, 'Geography', 2);

在上面的代码中,可能有很多书籍,我们不想加载书籍行。因此,我们在where子句中使用rownum。有没有一种方法,我们可以使用rownum,并获得正确的计数,从雇员表只,虽然我们做了一个连接?

select distinct b.EMP_ID from EMPLOYEE e , Books b
where e.EMPLOYEE_ID= b.EMP_ID
and rownum <= 2;

select count(distinct b.EMP_ID) from EMPLOYEE e , Books b
where e.EMPLOYEE_ID= b.EMP_ID
and rownum <= 2;

**Expected output:**

     EMP_ID
----------
         1
         2
rjee0c15

rjee0c151#

books表必须以某种方式参与-我建议exists

SQL> select * from employee order by employee_id;

EMPLOYEE_ID NAME
----------- ---------------
          1 James
          2 John
          3 Littlefoot   --> no rows for this EMPLOYEE_ID in BOOKS table
             
SQL> select * from books order by emp_id;

ID BOOKNAME                 EMP_ID
-- -------------------- ----------
1  JAVA                          1
2  CProgramming                  1
3  JSP                           1
4  Accountancy                   2
5  History                       2
6  Geography                     2

6 rows selected.

要查找其ID存在于BOOKS表中的员工,请运行

SQL> select e.employee_id
  2  from employee e
  3  where exists (select null
  4                from books b
  5                where b.emp_id = e.employee_id
  6               );

EMPLOYEE_ID
-----------
          1
          2              --> as expected, no EMPLOYEE_ID = 3 in result set

SQL>

相关问题