LoginSignup
9
9

More than 5 years have passed since last update.

みんなの為のMySQLまとめ(2)

Last updated at Posted at 2015-02-05

参考
http://homepage2.nifty.com/sak/w_sak3/doc/sysbrd/mysql_07.htm

■テーブルクリア

・テーブル中のデータだけを全て削除するには、delete 文を使用する。

delete from testm;

・但し、単純クリアが目的なら、この方法はレスポンス的に問題がある。
トランザクション機能が働くので、全レコードのトランザクションバッファ
への書き込みとコミットによる更新が行われる。
何万件にも及ぶデータのクリアを delete 文でやると実用に耐えない。

・単純なテーブルクリアが目的の場合は、表切り捨て(truncate) を使用する
と良い。この方が一瞬でクリアできる。

truncate table testm;

・思いきって、テーブル削除と再作成を利用する手もある。

drop table testm;
create table testm (
  key1           char(008),
  data1          int8,
  data2          int8,
  data3          int8
)

■テーブル定義変更(テーブル属性変更、列定義変更)

・データ項目の桁数が足りなくなったり、新たな項目を追加するのは alter
文で簡単に行える。但し、列名の変更はできないようである。

・新たにテーブルに項目を追加(列の追加、フィールド追加、カラム追加)
するには、次のようにする。

alter table testm add
  newdata1  int8
;

alter table testm add (
  newdata1  int8,
  newdata2  int8
);

  ・MySQL は列の削除が行える。

alter table testm drop
  newdata1
;

■整合性制約定義、リレーション、リファレンス、外部キー

・データ項目に他のテーブルとのリレーションをとって、制約条件などを設定
することができる。(constraints)
制約追加は、create table 時、または、alter table で行う。

・列制約には、
primary key 主キー制約(unique & not null)
unique 一意キー制約(ユニーク項目、一意制約、ユニーク値、ユニークキー、ユニーク制約)
not null NOT ヌル制約
check チェック制約
references 参照整合性制約(参照制約、外部整合性制約、外部制約キー)
がある。
not null 制約については、Oracle と構文が違うのか、alter table で変更
できないようである。
また、references 節約はサポートされていない。

alter table testm add unique (
  data1
);

alter table testm
  add constraint TESTM_JCSU check(data1 >= 0)
;

・MySQL では、制約単体の削除はできないようである。

■名前変更(テーブル名変更)

・テーブル名の変更は、次のようにする。

alter table testm rename to abc;
9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9