DB/SQL/射影と選択
列の選択†
指定した表から、指定した列を抽出する(射影)。
- 方法
-- piyo 表の全ての列を選択 select * from piyo; -- piyo 表の hoge 列を選択 select hoge from piyo; -- piyo 表の hoge 列と fuga 列を選択 select hoge, fuga from piyo;
行の選択†
指定した表から、指定した行を抽出する(選択)。
- 方法
-- 基本はこう select hoge from piyo where <条件> -- 使える演算子はこんなの。各文の select 〜 from 〜 は省略 where fuga = 'hoge' -- fuga 列が文字列 hoge where fuga = 100 -- fuga 列が 100 where fuga > 100 -- fuga 列が 100 より大きい where fuga >= 100 -- fuga 列が 100 以上 where fuga < 100 -- fuga 列が 100 より小さい where fuga <= 100 -- fuga 列が 100 以下 where fuga <> 100 -- fuga 列が 100 ではない -- こういうのも使える -- それぞれ not を入れればそれぞれの条件の否定がとれる where fuga [not] between 100 and 200 -- fuga 列が 100 から 200 の間 where fuga [not] in ('hoge', 'fuga', 100, 200) -- fuga 列が "hoge"、"fuga"、100、200 のいずれか where fuga [not] like '_b%' -- fuga 列の 2 文字目が "b" where fuga [not] like '%HOGE\_%' escape '\' -- fuga 列に "HOGE_" を含む where fuga is [not] null -- fuga 列が null -- あんまり使わないかもなパタン -- 副問い合わせの時に使うかも -- それぞれ not を入れれば否定になる where fuga > [not] any (100, 200, 300) -- fuga 列が 100 か 200 か 300 のどれかより大きい where fuga < [not] any (100, 200, 300) -- fuga 列が 100 か 200 か 300 のどれかより小さい where fuga = [not] any (100, 200, 300) -- fuga 列が 100 か 200 か 300 のどれかと等しい(IN と同じ) where fuga > [not] all (100, 200, 300) -- fuga 列が 100 と 200 と 300 のすべてより大きい where fuga < [not] all (100, 200, 300) -- fuga 列が 100 と 200 と 300 のすべてより小さい -- 複数条件指定は and もしくは or。優先順位はカッコで指定可能 -- 通常は and が優先。 where fuga > 100 and fuga < 200 where fuga > 100 and ( fuga < 200 or foo < 100 )- like の特殊文字の意味はこんな。特殊文字そのものを検索したいときは escape する
記号 意味 % 0文字以上の任意の文字列 _ 1文字の任意の文字
- like の特殊文字の意味はこんな。特殊文字そのものを検索したいときは escape する
列に別名をつける†
抽出する列に別名を付ける。画面に表示する名前を指定するほか、ソートの列指定(後述)にも使える。
- 方法
-- ダブルクオートで囲むと大文字小文字を区別。この場合は fuga になる select hoge as "fuga" from piyo; -- 囲まなければ大文字。FUGA select hoge as fuga from piyo; -- as は省略も可能 select hoge "fuga" from piyo; select hoge fuga from piyo;
列を連結する†
出力する列を好きに連結して整形する。
- 方法
-- ただ単にくっつけて出力する select hoge || fuga from piyo; -- 間に何か文字列を入れるときはシングルクオート select hoge || ' is a ' || fuga from piyo;
行の重複を省く†
同じ行がいっぱいあったら一行にまとめる。
- 方法
-- 基本はこう select distinct hoge from piyo; -- こうすると hoge と fuga の組で重複を省く。ある列でだけの重複排除は不可 select distinct hoge, fuga from piyo;
行をソートする†
出力する行を順序よく並べる。
- 方法
-- 基本はこう。hoge 列でソート(昇順) select hoge, fuga from piyo order by hoge; -- 昇順にソート(デフォルト) order by hoge asc -- 降順にソート order by hoge desc -- 複数列を指定してソート。この例では fuga 順にソートされた状態で hoge 順に並ぶ order by hoge, fuga -- ソート条件には列別名を使用可能 select hoge as fuga from piyo order by fuga;
Last-modified: 2011-10-17 (月) 20:04:52