oracle中两个表的记录匹配

cuxqih21  于 2023-01-30  发布在  Oracle
关注(0)|答案(1)|浏览(175)

我有下面两张table。

create table main_supplier(file_id number,process_id number,supplier_code
number);
create table addition_supplier(file_id number,process_id number,supplier_code
number);

insert into main_supplier values(1,2,4567);
insert into main_supplier values(1,2,1234);
insert into main_supplier values(1,2,5890);


insert into addition_supplier values(1,2,7890);
insert into addition_supplier values(1,2,1234);
insert into addition_supplier values(1,2,5890);

在上表中,main_supplier表中的supplier_code不应存在于addition_supplier www.example.com中的supplier_code中table.so我在plsql块中写入了一个游标。

cursor c1 select ta.supplier_code
  from main_supplier ta
  where ta.file_id=1
  and ta.process_id= 2
  and  exists(select 1
                 from addition_supplier sa
                 where  sa.file_id=ta.file_id
                        and sa.process_id= ta.process_id 
                 and sa.supplier_code=ta.supplier_code);
open c1;
loop
 fetch c1 into a;
   if a is not null then
     raise error;
   end if;
end loop;

上述选择查询是否正确?

umuewwlo

umuewwlo1#

查询本身有效。不知道您要做什么,因为您的查询结果是:
| 供应商代码|
| - ------|
| 1234|
| 小行星5890|
这是EXISTS()条件的结果-如果这是你要找的,那么,是的,你的SQL是好的,你得到了表中不应该存在的行-你将如何处理它们取决于你。你的(示例)PL/SQL代码将在第一行引发错误并退出。但这只是一个示例,希望...
试验

WITH 
    main_supplier  (FILE_ID, PROCESS_ID, SUPPLIER_CODE)     AS
        (
            Select 1, 2, 4567 From Dual Union All
            Select 1, 2, 1234 From Dual Union All
            Select 1, 2, 5890 From Dual 
        ),
    addition_supplier (FILE_ID,PROCESS_ID,SUPPLIER_CODE)    AS
        (
            Select 1, 2, 7890 From Dual Union All
            Select 1, 2, 1234 From Dual Union All
            Select 1, 2, 5890 From Dual 
        )

    SELECT    ta.SUPPLIER_CODE
    FROM      main_supplier ta
    WHERE     ta.FILE_ID=1  and ta.PROCESS_ID = 2 and  
            Exists(Select   1
                   From     addition_supplier sa
                   Where    sa.FILE_ID = ta.FILE_ID And sa.PROCESS_ID = ta.PROCESS_ID  And sa.SUPPLIER_CODE = ta.SUPPLIER_CODE)

SUPPLIER_CODE
-------------
         1234 
         5890

获得此结果的另一种方法是使用INNER JOIN ...

SELECT    ta.SUPPLIER_CODE
    FROM      main_supplier ta
  INNER JOIN  addition_supplier sa 
              ON( sa.FILE_ID = ta.FILE_ID And sa.PROCESS_ID = ta.PROCESS_ID  And sa.SUPPLIER_CODE = ta.SUPPLIER_CODE)
    WHERE     ta.FILE_ID=1  and ta.PROCESS_ID = 2 

SUPPLIER_CODE
-------------
         1234 
         5890

相关问题