カラムの変更いろいろ

 作成したテーブルのカラム属性やカラム名などを途中からでもいろいろ変更できます。(でも一番いいのはきちんと設計して最初から設定しておくのがいいです。というのは、途中からカラムのいろいろを変更するとデータに影響を及ぼし兼ねないからです。)しかし変更する内容によりけりでいろいろできます。

カラムのデータ型を変更する

 テーブル作成時には少なくとも一つのカラムを作成しなくてはならないのですが(当たり前)、そのカラムに対してデータ型を設定する必要があります。しかし途中でもう少し長いデータを挿入したいとか数字だけじゃなくて文字も入力したいとかなった時には変更できます。
alter table <テーブル名> modify <カラム名> <新しいデータ型>;
 新しいデータ型は以前のデータ型と同様のデータ型を指定しても大丈夫です。上書きされるだけみたいです。またこのコマンドを実行する際にはログイン後にデータベースの選択までしておかないと勿論ダメです。
$ mysql -u root -p (*1) まずはログイン
Enter password: (*2) パスワード入力
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 863
mysql> show databases; (*3) データベースを確認してみる 
+--------------------+
| Database           |
+--------------------+
| information_schema |
| my_db              |
| your_db            |
| his_db            |
| her_db            |
+--------------------+
mysql> use my_db; (*4) データベースを選択
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed (これでデータベースを選択できてます。)
mysql> show tables; (*5) テーブルを確認
+--------------------------+
| Tables_in_omnioo_user_db |
+--------------------------+
| my_table                 |
| 01_table                 |
| 02_table                 |
+--------------------------+
1 row in set (0.00 sec)
mysql> show columns from my_table; (*6) テーブルのカラムを確認
+----------------+--------------+------+-----+-----------+-------+
| Field          | Type         | Null | Key | Default   | Extra |
+----------------+--------------+------+-----+-----------+-------+
| number         | int(8)       | NO   | PRI | 0         |       |
| ID             | int(32)      | YES  |     | NULL      |       |
| family_name    | varchar(64)  | YES  |     | NULL      |       |
| first_name     | varchar(64)  | YES  |     | NULL      |       |
+----------------+--------------+------+-----+-----------+-------+
9 rows in set (0.00 sec)
mysql> alter table my_table modify number int(128); (*7) カラムのデータ型を変更
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0


オートインクリメントを指定する

 今まで手動で連番などを振っていたとしたらかなり面倒なのでオートインクリメントの指定をしておくとよいです。
alter table <テーブル名> modify <カラム名> <データ型> primary key not null auto_increment;
mysql> alter table system_user_information modify number int primary key not null auto_increment;
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

 オートインクリメントを指定するとデフォルトでは1から順番にナンバリングを始めます。もし途中の番号からはじめたい場合は途中の番号を指定することもできます。
alter table <テーブル名> auto_increment = <開始時の数字>;
mysql> alter table system_user_information auto_increment = 100;
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

 もしprimary key(主キー)が設定してある際にはオートインクリメントの設定ができない場合があるので最初にprimary keyを削除しておきます。
alter table <テーブル名> drop primary key;
mysql> alter table my_table drop primary key;
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0







プロフィール



  • Name :: 山上オサム ♂(37)
  • Hobby :: 武術
  • Work :: Web Designer