簡體   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