MySQLのテーブル作成と存在確認

MySQLのテーブル作成と存在確認

MySQLでテーブルを作成します。

create table文で作成します。

mysql> create table tbl_customer(
-> id int not null primary key,
-> firstname varchar(40) not null,
-> lastname varchar(40) not null,
-> age int default null
-> );
Query OK, 0 rows affected (1.82 sec)

mysql>

もう一度同じコマンドを実行してみます。

mysql> create table tbl_customer(
-> id int not null primary key,
-> firstname varchar(40) not null,
-> lastname varchar(40) not null,
-> age int default null
-> );
ERROR 1050 (42S01): Table 'tbl_customer' already exists
mysql>

すでにテーブルが存在する旨のエラーメッセージが出ます。

テーブルの重複を防ぐためにif not existsキーワードがあります。

mysql> create table if not exists tbl_customer(
-> id int not null primary key,
-> firstname varchar(40) not null,
-> lastname varchar(40) not null,
-> age int default null
-> );
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql>

これでエラーメッセージは表示されなくなります。

テーブルの存在確認するにはshow tablesを実行します。

mysql> show tables;
+------------------+
| Tables_in_testdb |
+------------------+
| tbl_customer     |
+------------------+
1 row in set (0.00 sec)

mysql>

テーブル定義を見たい場合はdescribe テーブル名、とタイプします。

mysql> describe tbl_customer;
+-----------+-------------+------+-----+---------+-------+
| Field     | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| id        | int(11)     | NO   | PRI | NULL    |       |
| firstname | varchar(40) | NO   |     | NULL    |       |
| lastname  | varchar(40) | NO   |     | NULL    |       |
| age       | int(11)     | YES  |     | NULL    |       |
+-----------+-------------+------+-----+---------+-------+
4 rows in set (0.01 sec)

mysql>

コメント

タイトルとURLをコピーしました