レコードの追加
全フィールド追加
INSERT INTO ~ VALUESコマンドで、全フィールドの内容をフィールドの順番通りに追加する。
|
1 |
INSERT INTO [テーブル名] VALUES([フィールド値1], [フィールド値2], ...); |
以下、実行例。
|
1 2 3 4 5 6 7 8 9 10 11 12 |
mysql> insert into test values('John', 32); Query OK, 1 row affected (0.00 sec) mysql> select * from test; +------+------+ | name | age | +------+------+ | John | 32 | +------+------+ 1 row in set (0.00 sec) mysql> |
フィールドを指定した追加
フィールドを指定した実行は次の通り。
|
1 |
INSERT INTO [テーブル名] ([フィールド名1], ...) VALUES([フィールド値1], ...); |
以下、実行例。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
mysql> insert into test (name, age) values('Alex', 40); Query OK, 1 row affected (0.00 sec) mysql> select * from test; +------+------+ | name | age | +------+------+ | Alex | 40 | | John | 32 | +------+------+ 2 rows in set (0.00 sec) mysql> |
フィールドの一部だけを指定すると、指定していないフィールドには初期値が設定される。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
mysql> insert into test (name) values('Alice'); Query OK, 1 row affected (0.11 sec) mysql> select * from test; +-------+------+ | name | age | +-------+------+ | Alex | 40 | | Alice | NULL | | John | 32 | +-------+------+ 3 rows in set (0.00 sec) mysql> |
レコードの変更
レコードのフィールド値の変更はUPDATE ~ SET ~ WHEREコマンドを使う。
|
1 |
UPDATE test SET age=28 WHERE name='Alice'; |
以下、実行例。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
mysql> update test set age=28 where name='Alice'; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from test; +-------+------+ | name | age | +-------+------+ | Alex | 40 | | Alice | 28 | | John | 32 | +-------+------+ 3 rows in set (0.00 sec) mysql> |
UPDATEの注意点
UPDATEコマンドは必ずWHEREで対象となるレコードを指定する。さもないと、全レコードのフィールドが指定した内容で変更されてしまう。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
mysql> update test set age=30; Query OK, 3 rows affected (0.11 sec) Rows matched: 3 Changed: 3 Warnings: 0 mysql> select * from test; +-------+------+ | name | age | +-------+------+ | Alex | 30 | | Alice | 30 | | John | 30 | +-------+------+ 3 rows in set (0.00 sec) mysql> |
レコードの削除
レコードの削除は、DELETE FROM ~ WHEREコマンドで行う。
|
1 |
DELETE FROM [テーブル名] WHERE [フィールド名]=[フィールド値]; |
以下、実行例。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
mysql> delete from test where name='John'; Query OK, 1 row affected (0.01 sec) mysql> select * from test; +-------+------+ | name | age | +-------+------+ | Alex | 30 | | Alice | 30 | +-------+------+ 2 rows in set (0.00 sec) mysql> |
DELETEの注意点
DELETEコマンドでWHEREを省略すると、全データが削除されてしまうので注意。
|
1 2 3 4 5 6 7 |
mysql> delete from test; Query OK, 2 rows affected (0.00 sec) mysql> select * from test; Empty set (0.00 sec) mysql> |