插入表需要来自另一个表的特定条件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了插入表需要来自另一个表的特定条件相关的知识,希望对你有一定的参考价值。
我有两个具有以下架构的SQL表:
road_test
(test_ID,考官ID,student_ID,vin,test_date)lessons_count
(学生ID,课程)
我正在寻找某种方法,要求学生至少有5个lessons_taken
才能插入road_test
表。
是否存在某种允许这样做的触发器或约束条件?
这是我的建议:
SQL> -- the final table
SQL> create table road_test
2 (test_id number, student_id number, vin number);
Table created.
SQL> -- table that shows which lessons were taken by which student
SQL> create table lesson
2 (student_id number, lesson_id number);
Table created.
SQL>
应该控制您是否允许将学生的记录插入road_test
表中的触发器:对所上课的数量进行计数,如果它太低(为了简单起见,我将其设置为3):]]
SQL> create or replace trigger trg_bi_road 2 before insert on road_test 3 for each row 4 declare 5 l_cnt number; 6 begin 7 select count(*) 8 into l_cnt 9 from lesson 10 where student_id = :new.student_id; 11 if l_cnt < 3 then 12 raise_application_error(-20001, 13 'You have to take at least 3 lessons'); 14 end if; 15 end; 16 / Trigger created. SQL>
测试(正如我所说:为简单起见,仅限于3节课:]
SQL> -- initial record SQL> insert into lesson(student_id, lesson_id) values (1, 100); 1 row created. SQL> -- can I enter that student into the ROAD_TEST table? Nope SQL> insert into road_test (test_id, student_id, vin) values (555, 1, 123456); insert into road_test (test_id, student_id, vin) values (555, 1, 123456) * ERROR at line 1: ORA-20001: You have to take at least 3 lessons ORA-06512: at "SCOTT.TRG_BI_ROAD", line 9 ORA-04088: error during execution of trigger 'SCOTT.TRG_BI_ROAD' SQL> -- Let's insert 2 more lessons for the same student SQL> insert into lesson(student_id, lesson_id) values (1, 200); 1 row created. SQL> insert into lesson(student_id, lesson_id) values (1, 300); 1 row created. SQL> -- New attempt for the ROAD_TEST table: SQL> insert into road_test (test_id, student_id, vin) values (555, 1, 123456); 1 row created. SQL> select * From lesson; STUDENT_ID LESSON_ID ---------- ---------- 1 100 1 200 1 300 SQL> select * from road_test; TEST_ID STUDENT_ID VIN ---------- ---------- ---------- 555 1 123456 SQL>
以上是关于插入表需要来自另一个表的特定条件的主要内容,如果未能解决你的问题,请参考以下文章
Redshift:使用来自另一个表的随机数据更新或插入列中的每一行