mysqlでテーブルを作成する
以下のように「create table」コマンドを使用しまs。
プライマリキーの指定は、「PRIMARY KEY(キー名)」で行います。
1 2 3 4 5 6 7 8 9 10 11 12 |
mysql> create table kamo_table (id int,name text not null,update_ts TIMESTAMP NOT NULL,PRIMARY KEY(id)); Query OK, 0 rows affected (0.04 sec) mysql> show table status; +------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+------------------+----------+----------------+---------+ | Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment | +------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+------------------+----------+----------------+---------+ | kamo_table | InnoDB | 10 | Compact | 0 | 0 | 16384 | 0 | 0 | 5242880 | NULL | 2017-08-31 00:24:20 | NULL | NULL | ujis_japanese_ci | NULL | | | +------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+------------------+----------+----------------+---------+ 1 row in set (0.00 sec) mysql> |
以下のようにプライマリキーに存在しないキーを指定すると、エラーとなります。
1 2 3 |
mysql> create table kamo_table2 (id int,name text not null,update_ts TIMESTAMP NOT NULL,PRIMARY KEY(id2)); ERROR 1072 (42000): Key column 'id2' doesn't exist in table mysql> |
プライマリキーの指定はキーの定義位置は特に関係ありません。
以下の例では、プライマリキーの指定を、キー自体の定義の前に持ってきています。
1 2 3 4 |
mysql> create table kamo_table3 (id int,PRIMARY KEY(nid),name text not null,nid int); Query OK, 0 rows affected (0.01 sec) mysql> |
カラムを見ると正しく定義されていることがわかります。
1 2 3 4 5 6 7 8 9 10 11 |
mysql> show columns from kamo_table3; +-------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | | name | text | NO | | NULL | | | nid | int(11) | NO | PRI | 0 | | +-------+---------+------+-----+---------+-------+ 3 rows in set (0.00 sec) mysql> |