6.テーブルを更新する

■レコードを更新する
mysql> update テーブル名 set カラム名1="値1" where カラム名2=値2;
例)mysql> update ex_table set ex_c="aaa" where ex_c_2=1;
※「ex_c_2」のデータが「1」のレコードの「ex_c」のデータを「aaa」に更新。

■レコードを削除する
mysql> delete from テーブル名 where カラム名=;
例)mysql> delete from ex_table where ex_c=2;
※「ex_c」のデータが「2」のレコードを削除。

■複数のテーブルを連携して削除する
例)mysql> delete table1,table2 from table1,table2 where table1.id1=1 and table1.data1=table2.data2;
※table1のid1カラムが1のレコードと、table2のdata2カラムにtable1のdata1と同じ値を持つレコードを削除。

■全てのレコードを削除する
mysql> truncate table テーブル名
例)mysql> truncate table テーブル名;
※ WHERE 句を用いないdeleteと同じだがtruncateの方が早い。

■ファイルからデータ入力(CSV)
mysql> load data infile "ファイルパス/ファイル名.csv"
-> into table テーブル名 fields terminated by "," lines terminated by "\n";
例)mysql> load data infile "/home/syokunin/ex.csv"
   -> into table ex_table fields terminated by "," lines terminated by "\n";

1行目が項目などのデータが入ったCSVファイルの場合。
例)mysql>load data infile "/home/syokunin/ex.csv"
-> into table ex_table fields terminated by "," lines terminated by "\n" ignore 1 lines;

■他のテーブルのデータを入力
mysql> insert into テーブル名(入力) select * from テーブル名(出力);
例)mysql> insert into ex_table_copy select * from ex_table;

カラムを個別に指定して入力
mysql> insert into テーブル名(カラム名1-2,カラム名2-2) select カラム名1-1,カラム名2-1 from ex_table;
例)mysql> insert into ex_table_copy(ex_c1_copy,ex_c2_copy) select ex_c1,ex_c2 from ex_table;

戻る | CGI'sトップへ戻る