リレーショナルデータベース

正規化

正規化とは:データベースにおいて重複項目をなくすこと
http://www.annyys.net/html/kihon_002.htm
第三正規化がよく使われる。

操作の種類

  • データ定義DDL

creat:データを格納するテーブル作成

alter:変更

drop:削除

  • データ操作DML(プログラムにおいて一番使う)

select:データの操作

insert:追加

update:更新

delete:削除

  • データ制御DCL

commit:トランザクション処理の確定

rollback:トランザクションの戻し

これら操作をSQLという言語で行う。

命令

select*from postcode where post_7
in('1500011','1500032','1500060');

in('候補1','候補2')
候補に該当するものを表示する

select*from postcode where post_7

not in('1500011','1500032','1500060');

not in('候補1','候補2')
候補にないものを全て表示

select count(*) from postcode;

表の中にある行数を下さい。
初めていじるテーブルに対して、select *をする前に
select count(*) from postcode;
しておいたほうがいい。
理由:データが多すぎるとプログラムが重くなるので、
まずどれくらいのデータ量があるのかを把握しておく。

insert into postcode (場所1,場所2) values('値1','値2');

postcodeというテーブルの、場所1に値1を、場所2に値2を入れ、行を追加する

select*from postcode where post_7 like '3%' order by addr2 desc addr3;

まずはaddr2の順序で並べ、同順のものがあればaddr3の順序で並べる。

update postcode set addr1='hoge',addr2='hage' where post_7='3760001';

データの更新
updateするときは、同じ条件で必ずいったんselectして対象のレコードを確認する。

delete from postcode where post_7='3760001';

データ削除
deleteするときは、同じ条件で必ずいったんselectして対象のレコードを確認する。

select price as 価格 from Products;

見出し「price」を「価格」に変更

select price * 1.05 as 税込価格 from Products;

直接計算できる。

select avg(Price),max(Price),min(Price) from Products;

平均、最大、最小値を計算。しかしあまりSQLで計算をさせたりせず、
プログラム側で色々と処理した方がよいことが多い。
管理のしにくさ、見づらさが大きな理由。

select avg(price),max(price),min(price) from Products group by CategoryID;

カテゴリIDごとに、平均、最大、最小値を出している。

select * from products where categoryid=1;

カテゴリIDが1のものを表示。

select avg(price),max(price),min(price) from Products where price>400 group by CategoryID;

priceが400を超える行を持ってきて、その中の平均、最大、最小を選ぶ

select CategoryID,count(*),
avg(price),max(price),min(price) from Products
where price>400
group by CategoryID having count(*)>2;

全体で400以上のものを選び、
グループ化した後でcountが2以上のものを選ぶ。

select CategoryID,count(*),
avg(price),max(price),min(price) from Products
where price>400
group by CategoryID;

priceが400以上のものでカテゴリごとに何行あるかを表示