2012-05-11 68 views
0

我有演員和人之間的IS-A關係。如何爲IS-A關係編寫插入語句(SQL)?

我明白如何爲PERSON編寫插入語句。但我如何將 連接到ACTOR?

編輯:澄清,有沒有辦法做到這一點,除了手動設置關係?

CREATE TABLE person 
(
    person_id  INT, 
    person_name VARCHAR(20), 
    birth_year CHAR(4), 
    gender  CHAR(1), 
    PRIMARY KEY(person_id) 
); 

CREATE TABLE actor 
(
    actor_id  INT NOT NULL REFERENCES person(person_id), 
    PRIMARY KEY(actor_id) 
); 
+0

使用數據庫支持該範式(OOP,繼承)。 http://www.postgresql.org/docs/9.1/static/ddl-inherit.html –

回答

2

這取決於你如何確定誰是演員。如果在插入person表時已經知道這一點,那麼您可以使用另一個INSERT語句將該行插入到actor表中。

如果您已經定義的人表,要識別特定的人,並將其標記爲演員(按名稱IE),你可以這樣做:

INSERT INTO actor (actor_id) 
    SELECT person_id  
    FROM person 
    WHERE person_name = 'Will Smith'; 

http://sqlfiddle.com/#!2/ce898/9

無論哪種方式,只要actor中的actor_id與person_id中的有效person_id匹配,INSERT就會有效。如果不存在相應的person_id,則INSERT將失敗。

+0

啊。好的。即使建立關係時,我是否也必須刪除陳述? – user1002563

2

如果萬一你正在使用Postgres的,你可以做繼承,就像在面向對象:

CREATE TABLE person 
(
    person_id  serial primary key, 
    person_name VARCHAR(20), 
    birth_year CHAR(4), 
    gender  CHAR(1) 
); 


create table actor 
(
    role text 
) inherits(person); 

測試:

insert into person(person_name,birth_year,gender) 
values('john lennon','1940','M'); 


insert into actor(person_name,birth_year,gender,role) 
values('johnny depp','19xx','M','hacker'); 


insert into actor(person_name,birth_year,gender,role) 
values('johnny walker','19xx','M','walker'); 


select * from person order by person_name; 

select * from actor order by person_name; 


Output: 


PERSON_ID PERSON_NAME  BIRTH_YEAR GENDER 
1   john lennon  1940  M 
2   johnny depp  19xx  M 
3   johnny walker 19xx  M 


PERSON_ID PERSON_NAME  BIRTH_YEAR GENDER ROLE 
2   johnny depp  19xx  M  hacker 
3   johnny walker 19xx  M  walker 

---------------------------------------------------------------- 


update actor set 
    role = 'pirates', birth_year = 1963 
where person_name = 'johnny depp'; 

select * from person; 

select * from actor; 



Output: 

PERSON_ID PERSON_NAME  BIRTH_YEAR GENDER 
1   john lennon  1940  M 
2   johnny depp  1963  M 
3   johnny walker 19xx  M 



PERSON_ID PERSON_NAME  BIRTH_YEAR GENDER ROLE 
2   johnny depp  1963  M  pirates 
3   johnny walker 19xx  M  walker 




---------------------------------------------------------------- 


delete from actor where person_name = 'johnny depp'; 

select * from person; 

select * from actor; 


Output: 

PERSON_ID PERSON_NAME  BIRTH_YEAR GENDER 
1   john lennon  1940   M 
3   johnny walker 19xx   M 

PERSON_ID PERSON_NAME  BIRTH_YEAR GENDER ROLE 
3   johnny walker 19xx   M  walker 

現場測試:http://www.sqlfiddle.com/#!1/463f4/1

+0

我希望我的項目必須使用mySQL。 – user1002563

0

請試試這個

INSERT INTO ACTOR(ACTOR_ID)選擇P.PERSON_ID從人P左聯合演員A ON P.PERSON_ID = A.ACTOR_ID

由於 Rajath

+0

請通過提出更好的問題來幫助增加您獲得的答覆數量。謝謝! http://stackoverflow.com/questions/how-to-ask –