テーブルにプライマリーキーを追加する方法をご紹介します。
まずはテーブルのカラムを確認します。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
mysql> show columns from kamo_table; +-----------+-----------+------+-----+-------------------+-----------------------------+ | Field | Type | Null | Key | Default | Extra | +-----------+-----------+------+-----+-------------------+-----------------------------+ | id | int(11) | NO | | 0 | | | name | text | NO | | NULL | | | test_int2 | int(11) | NO | | NULL | | | update_ts | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP | | test_int | int(11) | NO | | NULL | | +-----------+-----------+------+-----+-------------------+-----------------------------+ 5 rows in set (0.00 sec) mysql> |
「Key」の箇所が空欄になっていることがわかります。
「id」列をPrimary Keyとして変更します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
mysql> alter table kamo_table add primary key(id); Query OK, 0 rows affected (0.01 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> show columns from kamo_table; +-----------+-----------+------+-----+-------------------+-----------------------------+ | Field | Type | Null | Key | Default | Extra | +-----------+-----------+------+-----+-------------------+-----------------------------+ | id | int(11) | NO | PRI | 0 | | | name | text | NO | | NULL | | | test_int2 | int(11) | NO | | NULL | | | update_ts | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP | | test_int | int(11) | NO | | NULL | | +-----------+-----------+------+-----+-------------------+-----------------------------+ 5 rows in set (0.00 sec) mysql> |
「id」の「Key」列に「PRI」として表示されていることが確認できます。