Query from the multiple tables
"SELECT" can also pick out the data using multiple tables.
I will introduce two of them.
(1)Join multiple tables
The SQL to join multiple tables and pick out the data is as follows.
SELECT Item FROM TableName, TableName, ・・・
WHERE Conditions for joining tables
After "FROM", describe the tables to be joined, separated by commas.
After "WHERE", describe the conditions for associating items between tables.
The conditions to join are mandatory.
For example, the SQL for picking out the student's name and each teacher's
name from the "Grade" table and "HomeroomTeacher" table is as follows.
SELECT Name, TeacherName FROM Grade, HomeroomTeacher
WHERE Grade.Class = HomeroomTeacher.Class
Besides there is a way using "JOIN" in the SQL.
・INNER JOIN
・OUTER JOIN
These are omitted here.
(2)Subquery
You may select the data from a table using other search result. This is called
a subquery. The SQL is as follows.
SELECT Item, ・・・ FROM TableName
WHERE Item IN (SELECT Item FROM TableName WHERE Conditions)
The select in parentheses is performed first to get the item. Then, the "IN"
clause determines whether the item matches them.
For example, the SQL for picking out the teacher's name of a class with a math
average score not less than 75 points for each class from the "Grade" table
and "HomeroomTeacher" table is as follows.
SELECT TeacherName FROM HomeroomTeacher
WHERE Class IN (SELECT Class FROM Grade GROUP BY Class
HAVING AVG(Math) >= 75)
【Commentary】
①The math average scores are as follows.
・Class 1 is 95 point.
・Class 2 is 70 point.
・Class 3 is 75 point.
②The classes picked out by the subquery are 1 and 3.
③The teacher's names for classes 1 and 3 are picked out from the
"HomeroomTeacher" table.
[Japanese]
複数のテーブルを用いたデータ取得
SELECTは、複数のテーブルを利用してデータを抽出することも可能です。
それを2つ紹介します。
(1)複数のテーブルを結合
複数のテーブルを結合してデータを抽出するSQLは、下記の通りです。
SELECT 項目名 FROM テーブル名, テーブル名, ・・・
WHERE テーブルを結合する条件
上記のように、FROMの後ろには、結合するテーブルをカンマで区切って記述します。WHEREの後ろには、テーブルの項目の中からどれとどれを関連付けるのかを記述します。結合する条件は必須です。
(例)「成績」テーブルと「担任」テーブルから、学生の氏名とそれぞれの
担任名を抽出する場合
SELECT 氏名, 担任名 FROM 成績, 担任
WHERE 成績.クラス = 担任.クラス
また、SQLでは「JOIN」を使った結合方法があり、
・内部結合(INNER JOIN)
・外部結合(OUTER JOIN)
などもありますが、ここでは割愛します。
(2)副問合せ
あるSELECTの結果に基づいて、別のテーブルをSELECTすることができます。これを副問合せといいます。そのSQLは下記の通りです。
SELECT 項目名, ・・・ FROM テーブル名
WHERE 項目名 IN (SELECT 項目名 FROM テーブル名 WHERE 条件)
カッコ内のSELECTが先に実行されて項目名を取得し、IN句によっていずれかと項目が一致するかどうかを判定します。
(例)「成績」テーブルと「担任」テーブルから、クラス毎の数学の平均点が75点以上のクラスの担任名を抽出する場合のSQL
SELECT 担任名 FROM 担任
WHERE クラス IN (SELECT クラス FROM 成績 GROUP BY クラス
HAVING AVG(数学) >= 75)
【考え方】
①数学の平均点は、
・クラス1が95点
・クラス2が70点
・クラス3が75点
です。
②カッコ内のSELECTで取得されるクラスは、1と3です。
③担任テーブルから、クラスが1と3の担任名が取得されます。