SAK 図書館
PostgreSQL 編7 - 問い合わせ、レコード参照、クエリ、select、like、count
■データベース問い合わせ
・リレーショナルデータベース(RDB) では、select 文を用いて、実に様々な
問い合わせが可能である。
・特定のデータを抜き出す指定は次のようにする。
この例では、key の先頭が「a」で始まるものだけが問い合わされる。
like は、部分一致を行う。
select
key,
data1,
data2,
data3
from testm
where key like 'a%'
order by key
;
・問い合わせ件数(照会件数)を引き取るには、次のようにする。
select count(*) from testm where key like 'a%';
・次の構文はエラーとなる。
select
key,
data1,
data2,
data3,
count(*) as ct
from testm
where key like 'a%'
order by key
;
・group by での count 構文は OK。
select
key,
sum(data1),
sum(data2),
sum(data3),
count(key) as ct
from testm
where key like 'a%'
group by key
;
・複数条件で抽出するには、次のようにする。
この例では、key が「a001」と「b002」のものが問い合わされる。
where 句には、and、or を複合条件指定できる。
() で囲まれた条件ほど優先順位が高い。
select
key,
data1,
data2,
data3
from testm
where key = 'a001' or key = 'b002'
order by key
;
select
key,
data1,
data2,
data3
from testm
where (key = 'a001' or key = 'b002') and data1 > 0
order by key
;
・項目指定に「*」を指定すると、全ての項目が含まれる。
select
*
from testm
where key like 'a%'
order by key
;
・特定の項目を見せたくないときは次のようにする。
この例では、data2 と言う項目がなくなる。
select
key,
data1,
data3
from testm
order by key
;
・項目名を異なった項目名に変更する場合は、次のようにする。
この例では、data1 と言う項目名が「abc」と言う項目名に変更されている。
select
key,
data1 as abc,
data3
from testm
order by key
;
・計算項目を作る場合は、次のようにする。
この例では、data1 + data2 の合計が「total」と言う項目名で追加される。
様々な SQL 関数を用いた計算項目が作成できる。
select
key,
data1 + data2 as total,
data3
from testm
order by key
;
・文字列の結合項目を作る場合は、次のようにする。
この例では、data1 と data2 の結合文字が「stritem」と言う項目名で追加
される。SQL 関数を用いたフォーマットなども可能である。
select
key,
data1 || data2 as stritem,
data3
from testm
order by key
;
■PostgreSQL 編、JAVA Servlet、JSP 編資料
■MySQL 編資料
■SQL 基礎編資料
■SQL 基礎実地編資料
■SQL チューニング編資料
■Oracle PL/SQL 編資料