在关联表中对这样的外键的约束?

时间:2016-02-04 07:53:57

标签: mysql sql oracle rdb

表A和B中有三个表A,B,C,列src是外键。 Table是A.ID和B.ID的关联表。

mysql中是否存在任何约束以确保插入表C的每一行必须遵循约束:A.src等于B.src以获取其ID

例如,如下表C中的,允许row 1 7,因为A.ID和B.ID的SRC都是35,但row 2 7是非法的,因为A的SRC ID为46,但B.ID为35。

Table A
ID  SRC
1   35
2   46
3   46

Table B
ID  SRC
6   46
7   35
8   46

Table C
A_ID    B_ID
1   7
3   6

是否可以设置任何约束或机制以确保插入表C的每一行都遵循常规?

感谢。

2 个答案:

答案 0 :(得分:0)

我不确定这一点,但我试过这个

INSERT INTO table_c
(SELECT
   a.ID,
   b.ID
 FROM
   table_a AS a INNER JOIN table_b AS b ON a.SRC = b.SRC
);

This适用于我将table_a和table_b中的ID插入table_c

答案 1 :(得分:0)

您可以使用物化视图在Oracle中执行此操作:

Oracle安装程序

CREATE TABLE A (
  ID NUMBER PRIMARY KEY,
  SRC NUMBER
);

CREATE TABLE B (
  ID NUMBER PRIMARY KEY,
  SRC NUMBER
);

CREATE MATERIALIZED VIEW LOG ON A
   WITH SEQUENCE, ROWID(id, src)
   INCLUDING NEW VALUES;

CREATE MATERIALIZED VIEW LOG ON B
   WITH SEQUENCE, ROWID(id, src)
   INCLUDING NEW VALUES;

CREATE MATERIALIZED VIEW AB_MV
   BUILD IMMEDIATE
   REFRESH FAST ON COMMIT
   AS SELECT a.id, b.id 
      FROM   a, b
      WHERE  a.src = b.src
      GROUP BY A.id, B.id;


ALTER TABLE AB_MV ADD CONSTRAINT AB_MV__A__B__PK PRIMARY KEY (A_ID, B_ID );

CREATE TABLE C (
  A_ID NUMBER REFERENCES A( ID ),
  B_ID NUMBER REFERENCES B( ID ),
  PRIMARY KEY ( A_ID, B_ID ),
  FOREIGN KEY ( A_ID, B_ID ) REFERENCES AB_MV ( A_ID, B_ID )
);

插入数据

INSERT INTO A
SELECT 1, 35 FROM DUAL UNION ALL
SELECT 2, 46 FROM DUAL UNION ALL
SELECT 3, 46 FROM DUAL;

INSERT INTO B
SELECT 7, 35 FROM DUAL UNION ALL
SELECT 6, 46 FROM DUAL UNION ALL
SELECT 8, 46 FROM DUAL;

SELECT * FROM AB_MV;
-- Will return zero rows as there has not been a commit.

COMMIT;

SELECT * FROM AB_MV;
-- Will return 5 rows.

INSERT INTO C VALUES ( 1, 7 );
-- 1 row inserted

INSERT INTO C VALUES ( 2, 7 );
-- Fails with ORA-02291: Integrity constraint violated - parent key not found.

您可以在MySQL中使用触发器填充AB_MV表(使用MERGE INTO来强制执行唯一性)来执行类似操作 - 尽管从A或{删除行的触发器{1}}可能会很有趣,因为B对可以来自多个ID值。