如何在SQL数据库中创建记录之间的关系?

时间:2013-04-19 12:43:32

标签: sql database relationship

假设我们有一个“人物”表:

ID  Name      Surname   Age
1   Thorvald  Benjamin  32
2   Addison   Impi      40

我们有一个“兼容性”表:

Person1_ID  Compatibility  Person2_ID
1           89             2

如何在Person1_ID的值和People表中的记录之间创建关系?在Person2_ID中也是一样的东西?

当您从数据库中获取数据时,编写S​​QL查询的好方法是什么,以便您可以获取有关Person1,Person2及其兼容性的信息?

我对数据库知之甚少,这可能是一个非常简单的问题。请耐心等待。

2 个答案:

答案 0 :(得分:2)

类似的东西:

SELECT
    A.Person1_ID, A.Compatibility, A.Person2_ID,
    B.Name AS Person1_name, B.Surname AS Person1_surname, B.Age AS Person1_age,
    C.Name AS Person2_name, C.Surname AS Person2_surname, C.Age AS Person2_age
FROM table_compatibility as A
LEFT JOIN table_people AS B
    ON A.person1_ID = B.ID
LEFT JOIN table_people AS C
    ON A.person2_ID = C.ID
WHERE A.Person1_ID = 1

答案 1 :(得分:1)

这是一个有效的例子。

drop table person_example cascade constraints;
drop table compatibility_example cascade constraints;

create table person_example (person_id number primary key, name varchar2(50),age number);

create table compatibility_example (compat_id number,person_id1 number, person_id2 number);
alter table compatibility_example add 
(
constraint fk_comp_per1 foreign key (person_id1) references person_example(person_id),
constraint fk_comp_per2 foreign key (person_id2) references person_example(person_id)
);

insert into person_example (person_id,name,age) values(1,'John',23);
insert into person_example (person_id,name,age) values(2,'Josh',24);

select * from person_example;


 PERSON_ID NAME                                                      AGE
---------- -------------------------------------------------- ----------
         1 John                                                       23
         2 Josh                                                       24

2 rows selected.

insert into compatibility_example (compat_id,person_id1,person_id2 ) values(1,1,2);

select * from compatibility_example;

 COMPAT_ID PERSON_ID1 PERSON_ID2
---------- ---------- ----------
         1          1          2
1 row selected.

set linesize 750
select compat_id,person_id1,person_id2,
p1.name person_1, p1.age age1, p2.name person_2, p2.age age2
 from 
compatibility_example ce 
left outer join person_example p1
on ce. person_id1=p1.person_id
left outer join person_example p2
on ce. person_id2=p2.person_id;


 COMPAT_ID PERSON_ID1 PERSON_ID2 PERSON_1                                                 AGE1 PERSON_2                                                 AGE2
---------- ---------- ---------- -------------------------------------------------- ---------- -------------------------------------------------- ----------
         1          1          2 John                                                       23 Josh                                                       24
1 row selected.