SAK 図書館
PostgreSQL 編9 - スカラー副問い合わせ、件数指定、OFFSET、LIMIT、HAVING
■スカラー副問い合わせ
・PostgreSQL でも、スカラー副問い合わせがサポートされている。
このスカラー副問い合わせは、広く応用できて非常に便利です。
尚、フィールドなど単一行の結果を戻す必要のある問い合わせを
単一行副問い合わせと呼ぶ。
(単1行副問い合わせ、単一行問い合わせ、単1行問い合わせ)
select
key,
(select key from testm b where key = a.code1)
from test2m a
;
key | ?column?
----------+----------
abc01 | a001
abc02 | a011
abc03 |
abc02 | a011
abc03 |
■インラインビュー
・インラインビューは、次のようにする。
select *
from (select * from testm where key like 'a%') a
where a.data1 > 0
;
■件数指定 OFFSET、LIMIT
・先頭から 3 件問い合わせるには、次のようにする。
access の top と同じことができる。
(TOP 10 取得、表示行制限、レコード数限定、件数指定、表示件数)
(1 レコード取得、1 件取得)
select * from testm
order by key
offset 0 limit 3
;
key | data1 | data2 | data3
----------+-------+-------+-------
a001 | 1 | 2 | 3
a011 | 1 | 2 | 3
b002 | 10 | 20 | 30
・先頭レコードを問い合わせるには、次のようにする。
select * from testm
where key like 'a%'
order by key
offset 0 limit 1
;
key | data1 | data2 | data3
----------+-------+-------+-------
a001 | 1 | 2 | 3
・最後から 3 件問い合わせるには、ソートオーダを逆にすれば良い。
select * from testm
order by key desc
offset 0 limit 3
;
key | data1 | data2 | data3
----------+-------+-------+-------
c003 | 100 | 200 | 300
b002 | 10 | 20 | 30
a011 | 1 | 2 | 3
■EXISTS
・副問い合わせが行を戻したか。
select * from testm a
where exists (select * from test2m b where b.code1 = a.key);
■HAVING
・集計結果に対する問い合わせ条件を指定する。
select key, count(*), sum(data1), avg(data1) from testm
group by key
having sum(data1) > 10;
key | count | sum | avg
----------+-------+-----+----------------
c003 | 1 | 100 | 100.0000000000
■USING
・項目で結合する。(この例は悪い。)
select * from test2m left join testm
using (key);
key | code1 | data1 | data2 | data3
----------+----------+-------+-------+-------
abc01 | a001 | | |
abc02 | a011 | | |
abc03 | z999 | | |
■CROSS JOIN
・Oracle の「,」標記と同じ。(クロス結合、クロスジョイン)
select * from test2m cross join testm
where test2m.code1 = testm.key;
key | code1 | key | data1 | data2 | data3
----------+----------+----------+-------+-------+-------
abc01 | a001 | a001 | 1 | 2 | 3
abc02 | a011 | a011 | 1 | 2 | 3
■NATURAL JOIN
・同じ名前の列を自然結合する。(ナチュラルジョイン)
(この例は悪い。)
select * from test2m natural left join testm;
key | code1 | data1 | data2 | data3
----------+----------+-------+-------+-------
abc01 | a001 | | |
abc02 | a011 | | |
abc03 | z999 | | |
■PostgreSQL 編、JAVA Servlet、JSP 編資料
■MySQL 編資料
■SQL 基礎編資料
■SQL 基礎実地編資料
■SQL チューニング編資料
■Oracle PL/SQL 編資料