从一个表引用到另一个整个表和指定的行

时间:2012-11-24 21:06:39

标签: sql postgresql

我有三个表:A,B和C.我想创建表A,它应该有3列,第一列应该是PRIMARY KEY

1)如何创建第二列,是对表B的引用,

2)和第三个是对表C中'C.id'行的引用.A.id = C.id

CREATE TABLE A
(
    id SERIAL PRIMARY KEY,
    // ? - reference to table B
    // ? - reference to C.id row. A.id = C.id
)

数据库:postgresql

1 个答案:

答案 0 :(得分:1)

我假设您使用的是mysql数据库。

CREATE TABLE A
(
    id INT NOT NULL PRIMARY KEY,
    b_id INT NOT NULL,
    c_id INT NOT NULL,
    FOREIGN KEY (b_id) REFERENCES B (id),
    FOREIGN KEY (c_id) REFERENCES C (id)
) TYPE = INNODB;

使用postgresql的更新:

CREATE TABLE "A"
(
   id integer NOT NULL, 
   b_id integer NOT NULL, 
   c_id integer NOT NULL, 
   CONSTRAINT id PRIMARY KEY (id), 
   CONSTRAINT b_id FOREIGN KEY (b_id) REFERENCES "B" (id) 
      ON UPDATE NO ACTION ON DELETE NO ACTION, --with no action restriction
   CONSTRAINT c_id FOREIGN KEY (c_id) REFERENCES "C" (id) 
      ON UPDATE CASCADE ON DELETE CASCADE  --with cascade restriction
) 
WITH (
  OIDS = FALSE
)
;
ALTER TABLE "C" OWNER TO postgres;