vscode上でMySQLを使う方法については、以下の記事にまとめています。
目次
データベースへの接続
mysql -u root -p
基本スクリプト
既存データベースの確認
show databases;
データベースの作成
create database <name>;
データベースの削除
drop database <name>;
データベースの選択
use <name>;
現在のデータベースの確認
select database();
テーブルの作成
create table <tablename>(
col1 <dtype>,
col2 <dtype>
);
テーブルのリネーム
rename table <table_from> to <table_to>;
Nullableの制御
カラム作成の際に、データがnullでも良いかを指定。
create table <tablename>(
col1 <dtype> not null,
col2 <dtype> not null
);
Default値の指定
create table <tablename>(
col1 <dtype> default <value>,
col2 <dtype> default <value>
);
プライマリキーの指定
キーはユニークである必要があり、データの追加時に指定する必要あり。
create table <tablename>(
id primary key,
col1 <dtype>,
col2 <dtype>
);
または
create table <tablename>(
id int,
col1 <dtype>,
col2 <dtype>,
primary key(id)
);
プライマリキーのオートインクリメント
create table <tablename>(
id int AUTO_INCREMENT,
col1 <dtype>,
col2 <dtype>,
primary key(id)
);
全テーブルの表示
show table;
テーブルの中身(カラム)の表示
show columns from <tablename>;
または
desc <tablename>;
crud処理
テーブルにデータを追加
カラムと値が一致していればOK。
insert into <tablename>
(col1,col2)
values(
'value1',
'value2'
);
テーブルに複数データを一括追加
insert into <tablename>
(col1,col2)
values
('val1',1),
('val2',2),
('val3',3),
('val4',4),
('val5',5);
テーブルデータの取得
select * from <tablename>;
特定カラムのデータのみ取得
select <colname> from <tablename>;
複数カラムの取得
select <colname1>, <colname2> from <tablename>;
where構文
strとintに注意。カラム名はダブルクオーテーションなし。
select * from <tablename> where <colname> = <value>;
条件一致した特定のカラムのみの取得も行える。
select <colname> from <tablename> where <colname> = <value>;
各カラムネームにasを使用して変更を加えることもできる。
select <colname> as <new name> from <tablename> where <colname> = <value>;
update構文
update <tablename> set <colname> = <value> where <colname> = <value>;
delete構文
delete from <tablename> where <colname> = <value>;
テーブルの中身を全て削除。(テーブル自体は保持)
delete from <tablename>;
distinct構文
pythonのsetのような物。重複を無視してデータを全件取得。
select distinct <colname> from <tablename>;
オートインクリメントの初期化
alter table <tablename> auto_increment = 1;
カラムの追加(alter)
alter table <tablename> add column <colname> <dtype>;
カラムの削除(alter)
alter table <tablename> drop column <colname>;
データのエクスポート
cd <export path>
mysqldump -u root -p <database_name> > <export_name>.sql