SQL检查来自多个表的值

时间:2014-12-01 04:01:30

标签: sql oracle

如果我有2个这样的表:

Authors(
book char(30) PRIMARY KEY,
earnings INT
);
Books(
book char(30),
sales INT
FOREIGN KEY(book) REFERENCES Authors(book)
);

我如何编写一张支票来强制执行一本低于Oracle SQL中图书销售额的图书的收入?我会把它放在哪里,因为它使用了两个表中的值?

1 个答案:

答案 0 :(得分:0)

如果我了解你的病情"check to enforce earnings for a book to be less than sales for the book"是正确的,表中的主键和外键创建需要重新定位如下:

Rem -- Books Table
create table books(
     book char(30) primary key, 
     sales int
);

Rem -- Authors Table
create table authors (
     book char(30), 
     earnings int, 
     foreign key(book) references books(book)
); 

Rem -- Create a trigger to enforce the condition
Rem -- Earnings for a book should be less than sales
CREATE OR REPLACE TRIGGER check_earnings BEFORE
  INSERT ON authors FOR EACH ROW 
  DECLARE 
        earnings_higher_than_sales EXCEPTION;
        sales_val int;
  BEGIN
    select sales into sales_val from books where book=:new.book;
    dbms_output.put_line('Corresponding sales value:'||sales_val);
    IF :new.earnings > sales_val THEN
      RAISE earnings_higher_than_sales;
    END IF;
  EXCEPTION
  WHEN earnings_higher_than_sales THEN
    RAISE_APPLICATION_ERROR(-20000, 'Earnings values can''t be greater than sales');
END;
/

Rem -- Insert some rows into books
insert into books values('davinci code',100);
insert into books values('alchemist',200);
insert into books values('monk who sold his ferrari',300);
insert into books values('digital fortress',400);
insert into books values('unbowed',500);
commit;

Rem -- Insert some rows into authors
Rem -- Following two will succeed
insert into authors values('davinci code',90);
insert into authors values('alchemist',180);
Rem -- Following will fail, as the earnings(320) is greater than sales(300)
insert into authors values('monk who sold his ferrari',320);
Rem -- Following will succeed
insert into authors values('monk who sold his ferrari',290);
Rem -- Following two will succeed
insert into authors values('digital fortress',340);
insert into authors values('unbowed',400);
commit;

因此,答案是在表作者上插入或更新之前创建触发器。