繁体   English   中英

想要查询连接第一个表的第一行和第二个表的前两列

[英]want query to connect 1st table 1st row and 2nd table first two column

我想连接查询来连接第一张表的第一行和第二张表的前两列,

表A

ID     Date        Username  Password              
1    19/2/2016       XYZ       ******               
2    19/2/2016       ABC       ******    

表B,

ID     Date        Username    City                     
1    19/2/2016       XYZ       NYC                       
2    19/2/2016       ABC       LA                      

当我在表A的第一行中插入一些数据时,我想检查表B的ID,DATE是否有可用数据

您是说要在这两个表之间强制引用完整性吗? 在这种情况下,您需要一个外键约束

ALTER TABLE table_a
ADD CONSTRAINT reference_table_b_fk
   FOREIGN KEY (id, date)
   REFERENCES table_b (id, date);

如果您只想在执行“插入”选项之前进行检查,请尝试以下操作:

IF EXISTS (SELECT ID FROM TableB WHERE ID=1 AND Date='19/2/2016')

// Your either insert or not query

ELSE 

// Your else logic will be here 

因此,如果仅在table2中存在等效条目时才将条目插入到table1中,请执行以下脚本:

create table table1 (id number(2), date_t1 date, username varchar2(5), password varchar2(8));
create table table2 (id number(2), date_t1 date, username varchar2(5), city varchar2(8));

insert into table1 values (1, to_date('16.02.2016', 'dd.mm.yyyy'), 'XYZ', 'ABC123');
insert into table1 values (2, to_date('16.02.2016', 'dd.mm.yyyy'), 'ABC', 'XYZ123');

insert into table2 values (1, to_date('16.02.2016', 'dd.mm.yyyy'), 'XYZ', 'NYC');
insert into table2 values (2, to_date('16.02.2016', 'dd.mm.yyyy'), 'ABC', 'LA');


declare
  n_id number(2);
  d_date date;
  v_username varchar2(5);
  v_password varchar2(8);
  n_check number(1);
begin
  n_check := 0;
  -- fill the variables with data which you want to insert:
  n_id          := 2;
  d_date        := to_date('16.02.2016', 'dd.mm.yyyy');
  v_username    := 'ABC';
  v_password    := 'CCCCC';

  -- check whether an entry exists in table2:
  begin
    select count(1)
    into n_check
    from table2 t2
    where t2.id = n_id
    and trunc(t2.date_t1) = trunc(d_date);
  exception when no_data_found then n_check := 0;
  end;

  -- if an entry exists in table2, then insert into table1:
  if n_check <> 0 then
    insert into table1 (id, date_t1, username, password) 
    values (n_id, d_date, v_username, v_password);
  end if;
end;  
/

select * from table1;
select * from table2;

delete from table1;
delete from table2;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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