MySQL012 データの編集(サブクエリ)
chap10 つづき
■副問い合わせ(サブクエリ)
ークエリで取り出されたデータをつかいクエリを発行する。
ー1つ目の処理を()で囲む。
<値の返却>
・最大値をもつものを表示
select * from tb10 where uria=max(uria); //エラー
select max(uria) from tb10; //最大値の取得
select * from tb10 where uria in (select max(uria) from tb10);
//where ~ in ~
・平均以上のレコードを抽出
平均年齢以上の人
select * from tb11 where tosi >=(select avg(tosi) from tb11);
<カラムの返却>
・INを使う
200万以上の売上をもつ社員を抽出
select bang from tb10 where uria >= 200; //200万以上のレコード抽出
select * from tb11 where bang in (select bang from tb10 where uria >= 200);
・=をつかう場合
ー1件以上あるとエラーになる
ー1件以上あるとlimitを使ってもどの1件かわからない
ーorder byとlimitを掛け合わせれば=も利用可能
・存在するレコードだけを対象とする(EXISTS)
select * from tb10 where tb10.bang=tb11.bang;
select * from tb11 where exists
(select * from tb10 where tb10.bang=tb11.bang);
select * from tb11 where not exists
(select * from tb10 where tb10.bang=tb11.bang);
・順位づけ2
いったん除外
■参考
本:基礎からのMySQL