SAK 図書館
MySQL 編12 - 問い合わせ、集計、平均、最大、最小、重複、集合、複合
■集計問い合わせ(合計値)
・集計問い合わせを行うには、group by 句を使用する。
この例では、key1 の先頭が「a」で始まる明細を key1 単位に集計(サマリー)
し、data1 の合計が 10 以上のものを問い合わせる。
having 句は、集計後の結果に対して抽出条件が指定できる。
select key1, sum(data1) from testm
where key1 like 'a%'
group by key1
having sum(data1) >= 10
;
・count() を使用すると、合計件数が問い合わせられる。
(問い合わせ件数表示、照会件数表示、抽出件数)
この例では、key1 単位に集計し、data1 の合計が 10 以上のものを
問い合わせる。
select key1, count(*), sum(data1) from testm
group by key1
;
+------+----------+------------+
| key1 | count(*) | sum(data1) |
+------+----------+------------+
| a001 | 1 | 1 |
| a011 | 1 | 1 |
| b002 | 1 | 10 |
| c003 | 1 | 100 |
+------+----------+------------+
・単純に特定の明細のレコード件数を問い合わせるときは、次のように使用す
る。この例では、key1 の先頭が「a」で始まる明細の件数が得られる。
select count(*) from testm
where key1 like 'a%'
;
+----------+
| count(*) |
+----------+
| 2 |
+----------+
・avg を使用すると平均を問い合わせることができる。
この例では、key1 毎の data1 の平均が得られる。
select key1, avg(data1) from testm
group by key1
;
+------+------------+
| key1 | avg(data1) |
+------+------------+
| a001 | 1.0000 |
| a011 | 1.0000 |
| b002 | 10.0000 |
| c003 | 100.0000 |
+------+------------+
・max、min を使用すると最大値と最長値を問い合わせることができる。
この例では、key1 毎の data1 の最大と最小が得られる。
select key1, max(data1), min(data1) from testm
group by key1
;
+------+------------+------------+
| key1 | max(data1) | min(data1) |
+------+------------+------------+
| a001 | 1 | 1 |
| a011 | 1 | 1 |
| b002 | 10 | 10 |
| c003 | 100 | 100 |
+------+------------+------------+
■重複レコード除去(重複レコード削除)
・testm のキーがユニークでないと仮定すると、同じキーのレコードが複数
存在する事になる。
distinct を指定すると重複レコードを取り除いて問い合わせできる。
distinct の代わりに unique と Oracle のように指定することはできない。
(重複データ)
select distinct key1
from testm
;
+------+
| key1 |
+------+
| a001 |
| a011 |
| b002 |
| c003 |
+------+
■集合問い合わせ
・union all を使用すると問い合わせ結果をマージできる。
この例では、testm と testmsv の key1 の先頭が「a」で始まるものが問い
合わされる。union all の代わりに union とだけ指定すると、重複レコード
は含まれない。(表を合わせ、付け足す)
select * from testm
where key1 like 'a%'
union all
select * from testmsv
where key1 like 'a%'
;
select * from testm
where key1 like 'a%'
union all
select * from testm
where key1 like 'a%'
;
+------+-------+-------+-------+
| key1 | data1 | data2 | data3 |
+------+-------+-------+-------+
| a001 | 1 | 2 | 3 |
| a011 | 1 | 2 | 3 |
| a001 | 1 | 2 | 3 |
| a011 | 1 | 2 | 3 |
+------+-------+-------+-------+
select * from testm
where key1 like 'a%'
union
select * from testm
where key1 like 'a%'
;
+------+-------+-------+-------+
| key1 | data1 | data2 | data3 |
+------+-------+-------+-------+
| a001 | 1 | 2 | 3 |
| a011 | 1 | 2 | 3 |
+------+-------+-------+-------+
■集合差問い合わせ
・minus、minus all は、MySQL では使用できない。
■集合結合問い合わせ
・intersect は、MySQL では使用できない。
■複合問い合わせ
・in、any などを使用した複合問い合わせは、MySQL ではサポートされていな
いようである。そもそも副問い合わせがエラーになってしまう。
■MySQL 編資料
■PostgreSQL 編、JAVA Servlet、JSP 編資料
■SQL 基礎編資料
■SQL 基礎実地編資料
■SQL チューニング編資料
■Oracle PL/SQL 編資料