주 키와 외부 키를 만드는 명령

    ,           :
create table t1
(id int primary key, 
name varchar(20)
);

create table t2
(
remark varchar(50),
p_id int references t1(id) /*   p_id      t1  id*/
);

       :
1、t1 id   key
2、   2                    。
 
 
     ,        :
--       . ID    .
CREATE TABLE test_main (
id      INT,
value   VARCHAR(10),
PRIMARY KEY(id) 
);

--       . 
CREATE TABLE test_sub (
id      INT,
main_id INT,
value   VARCHAR(10),
PRIMARY KEY(id) 
);

        
ALTER TABLE test_sub ADD CONSTRAINT main_id_cons FOREIGN KEY (main_id) REFERENCES test_main;

DELETE CASCADE   
--     (   ON DELETE CASCADE   ,       ,      )
ALTER TABLE test_sub
  ADD CONSTRAINT main_id_cons
    FOREIGN KEY (main_id) REFERENCES test_main ON DELETE CASCADE;

UPDATE CASCADE  
--     (   ON UPDATE CASCADE   ,         ,        )
ALTER TABLE test_sub
  ADD CONSTRAINT main_id_cons
    FOREIGN KEY (main_id) REFERENCES test_main ON UPDATE CASCADE;

SET NULL  
--     (   ON DELETE SET NULL   ,       ,       main_id     NULL)
ALTER TABLE test_sub
  ADD CONSTRAINT main_id_cons
    FOREIGN KEY (main_id) REFERENCES test_main ON DELETE SET NULL;

좋은 웹페이지 즐겨찾기