2

「People」テーブルがあるとしましょう:

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 でも同じことですか?

また、データベースからデータを取得する場合、Person1、Person2、およびそれらの互換性に関する情報を取得できるように SQL クエリを記述するには、どのような方法がよいでしょうか?

私はデータベースについてあまり知りません。これはおそらく非常に簡単な質問です。我慢してください。

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 に答える