LoginSignup
0
0

SQLの基本その2(サブクエリ)

Posted at

サブクエリ

SQL文の中に別のSQL文を埋め込む手法がある。この埋め込まれたサブのSQLがサブクエリである。
studentsテーブルに五教科の点数が格納されているとする。例えば数学の点数が平均点より高い生徒の名前を表示したい場合は、下記のようになる。

select name from students where math > ( select avg(math) from students );

サブクエリの種類

サブクエリの内容によって取得できるデータの形態が異なる。
4パターンのサンプルを示す。

単一行×単一列

一意のレコードから単一の値を取得した場合。

-- 使用例(可読性のため改行)
select id, name where math >= 
  (select avg(math) from students where gender = 'm' group by gender);

単一行×複数列

1レコードだけのテーブルの代わりとして使うことが多い。

-- 使用例(可読性のため改行)
select name, math from students where (name, math) = 
  (select name, math from students where id = 1);

複数行×単一列

複数レコードから単一カラムの値を取得する。in演算子の右項として使用する。

-- 複数のレコードから単一の値を取得
select id, name from students where id in (select id from students where gender = 'm');

複数行×複数列

-- 複数のレコードから複数の値を取得。要するにテーブルを取得するイメージ。
-- from句の右項として使用する。このときサブクエリにaliasが必要(今回は t とした)。
select t.gender, t.avg(math)
  from (select gender, avg(math) from students group by gender) t;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0