2

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

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 也是一样的吗?

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

我对数据库了解不多,这可能是一个非常简单的问题。请多多包涵。

4

2 回答 2

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
于 2013-04-19T13:35:40.057 回答
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.
于 2013-04-19T15:32:18.967 回答