使用触发器作为过滤器从两个表联接中插入表

时间:2018-09-04 14:02:57

标签: sql oracle triggers

我正在使用oracle DB,并且以这两个表为例:

TABLE A :
ID     Phone   WEEK    MODEL
 1     10      14-18   XYX
 2     32      15-18   XXZ
 3     40      15-18   XYX
 4     19      16-18   ZZT
 5     10      14-18   XYX

 TABLE B :

 ID   MODEL    TRAFIC
  1   XYX      2G/3G
  2   XCA      2G/3G/4G
  3   ZZT      2G/3G/4G
  4   ABC      2G only
  5   XYZ      2G/3G
  6   XXZ      2G only


  TABLE C RESULTS of JOIN :

  ID   Phone   WEEK    MODEL   TRAFIC
 1     10      14-18   XYX     2G/3G
 2     32      15-18   XXZ     2G only
 3     40      15-18   XYX     2G/3G
 4     19      16-18   ZZT     2G/3G/4G

现在,我想将表B和表A(JOIN)中的行插入表C where (A.Phone != C.Phone and A.WEEK != C.WEEK)

这是插入的sql脚本,首先结果表C为空:

INSERT INTO C(PHONE, MODEL, TRAFIC, WEEK)
SELECT DISTINCT PHONE, WEEK, MODEL,TRAFIC
        FROM(SELECT WEEK, A.PHONE,A.MODEL,B.TRAFIC
            FROM A
            LEFT JOIN B ON B.model = A.model)
GROUP BY PHONE, WEEK;

我要在插入值时使用触发器,它将首先检查同一周是否已插入电话   谢谢。

1 个答案:

答案 0 :(得分:1)

您可以尝试以下代码,而无需使用触发器,而是比较数据组合的存在:

INSERT INTO C(PHONE, MODEL, TRAFIC, WEEK)
SELECT DISTINCT PHONE, WEEK, MODEL,TRAFIC
  FROM (SELECT A.WEEK, A.PHONE,A.MODEL,B.TRAFIC
          FROM A
          LEFT JOIN B ON B.model = A.model
         WHERE NOT EXISTS (SELECT 1
                             FROM C
                            WHERE C.PHONE = A.PHONE
                              AND C.WEEK = A.WEEK))
GROUP BY PHONE, WEEK;

据我所知,不可能阻止触发器内部的插入。如果您确实需要使用触发器,则可以制作一个AFTER INSERT TRIGGER,该操作将从C表中删除所有刚插入但不应该插入的行(使用另一个表来存储行将需要删除。)

我为该替代方法找到的示例可以在这里找到:

https://community.oracle.com/thread/484449?start=15&tstart=0