SQLの初心者です。


SQLの記述方法に関して、教えてください。

以下のような二つのテーブルがあるとします。table1には、担当のIDが記載されていて、
table2には担当のIDと名前が記載されています。


id,tanto1,tanto2
1,2,3
2,3,4
3,1,2


tid,name
1,山田
2,佐藤
3,河口
4,鈴木


これを以下のような形で表示させるには、どのようなSQLを書けばよいのでしょうか。

id,name1,name2
1,佐藤,河口
2,河口,鈴木
3,山田,佐藤


初歩の初歩の質問で申し訳ありませんが、宜しくお願いします。

回答の条件
  • 1人2回まで
  • 登録:
  • 終了:2010/03/24 12:30:04
※ 有料アンケート・ポイント付き質問機能は2023年2月28日に終了しました。

回答4件)

id:taknt No.1

回答回数13539ベストアンサー獲得回数1198

ポイント23pt

SELECT table1.id

, (select table2.name from table2 where table2.tid = table1.tanto1)

, (select table2.name from table2 where table2.tid = table1.tanto2)

FROM table1

それぞれ 抽出したデータで 再度 SELECT してやればいいです。

id:tomohirof

ありがとうございます!

なるほど勉強になります。

2010/03/23 19:03:01
id:aside No.2

回答回数339ベストアンサー獲得回数31

ポイント23pt
select  a.id, b.name, c.name
from    table1 a
,       table2 b
,       table2 c
where   a.tanto1 = b.id
and     a.tanto2 = c.id
select  a.id
,       (select b.name from table2 b where a.tanto1 = b.id)
,       (select c.name from table2 c where a.tanto2 = c.id)
from    table1 a
id:tomohirof

2種類の方法があるんですね。ありがとうございます。

2010/03/23 19:03:20
id:Km1967 No.3

回答回数224ベストアンサー獲得回数35

ポイント22pt

RDBMSにもよるが例えばPostgreSQLなら下記などになる。

別のRDBMSの場合は、返信欄に名称とバージョンを明記して他の回答者からの回答を待つよろし。

CREATE TEMPORARY TABLE table1 (id INT, tanto1 INT, tanto2 INT);
INSERT INTO table1 VALUES(1,2,3),(2,3,4),(3,1,2);
CREATE TEMPORARY TABLE table2 (tid INT, name TEXT);
INSERT INTO table2 VALUES(1,'山田'),(2,'佐藤'),(3,'河口'),(4,'鈴木');

SELECT a.id
  , (SELECT b.name FROM table2 b WHERE b.tid = a.tanto1 LIMIT 1) AS name1
  , (SELECT c.name FROM table2 c WHERE c.tid = a.tanto2 LIMIT 1) AS name2
FROM table1 a;
id:tomohirof

MYSQL を利用していました。教えていただいた考え方で対応できました!

2010/03/23 19:03:42
id:p332 No.4

回答回数36ベストアンサー獲得回数3

ポイント22pt

table1にある担当者IDが、table2にない場合に、その行を取得するかどうかで、2通りの書き方がありますので、2通りのSQLを示します。

その行を除外する場合は内部結合、担当者を空白としてその行を取得する場合は外部結合を用います。

いずれの場合も、ひとつのSQLにtable2を2回登場させるのが気づきにくい点かと思います。

--内部結合
select
	t1.id
,	t2_1.name name1
,	t2_2.name name2
from
	table1 t1
,	table2 t2_1
,	table2 t2_2
where  
	t1.tanto1 = t2_1.tid
and	t1.tanto2 = t2_2.tid
order by t1.id

--外部結合
select
	t1.id
,	t2_1.name name1
,	t2_2.name name2
from
	table1 t1
left outer join table2 t2_1 on (t1.tanto1 = t2_1.tid)
left outer join table2 t2_2 on (t1.tanto2 = t2_2.tid)
order by t1.id
id:tomohirof

ありがとうございました。我流でやっていると外部結合、内部結合、どうしても理解できません。。。。

2010/03/23 19:04:17

コメントはまだありません

この質問への反応(ブックマークコメント)

「あの人に答えてほしい」「この質問はあの人が答えられそう」というときに、回答リクエストを送ってみてましょう。

これ以上回答リクエストを送信することはできません。制限について

回答リクエストを送信したユーザーはいません