如何为IS-A关系编写插入语句(SQL)?

时间:2012-05-11 02:49:56

标签: sql

我和演员之间有IS-A关系。

我理解如何为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)
);

3 个答案:

答案 0 :(得分:2)

这取决于你如何确定谁是演员。如果您在插入人员表时已经知道这一点,那么您也可以使用另一个INSERT语句将行插入到actor表中。

如果您已经定义了人员表,并希望识别特定人员并将其标记为演员(即按名称),则可以执行以下操作:

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匹配,INSERT就会有效。如果不存在相应的person_id,则INSERT将失败。

答案 1 :(得分:2)

如果您使用Postgres,您可以进行继承,就像在OOP中一样:

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

答案 2 :(得分:0)

请试试这个

INSERT INTO ACTOR(ACTOR_ID)选择P.PERSON_ID从P P LEFT JOIN ACTOR A ON P.PERSON_ID = A.ACTOR_ID

由于 Rajath