MySQLコマンド
MySQLに入る
> cd C:\xampp\mysql\bin
> mysql -u root
データベースの作成
> create database product default character set utf8 collate utf8_general_ci;
データベース確認
> show database;
> select database();
データベース切り替え
> use product;
データベース削除
> drop database product;
テーブル作成
> create table users(
id int not null auto_increment primary key,
name varchar(255),
score int
);
テーブル構造の確認
> desc users;
データ確認
> select * from users;
ユーザー作成
> create user dbuser01@localhost identified by 'password';
ユーザー権限譲渡
> grant all on mydb01.* to dbuser01@localhost;
ユーザー確認
> select user();
ユーザー削除
> drop user dbuser01@localhost;
レコードのデータ挿入
> insert into users (id, name, score) values (1, 'john', 5.8);
フィールドに制限をかける
変なデータが入らないように
null のフィールドをはじく
> score float not null
=> データが null のときフィールドそのものがないことになる
データが無い時デフォルト値設定
> score float default 0.0
=> score が設定されていないとき、0.0の値が入る
重複がないようにする
> name varchar(20) unique
=> 重複したフィールドははじかれる
id に対する主キーの設定
> id int unsigned primary key auto_increment
primary key => null ではない重複しない値になることが保証される
auto_inctement => 自動的に連番になる
フィールドを後から追加
> alter table users add column email varchar(255);
末尾に after [フィールド名] とすると、指定したフィールドの直後に追加する
フィールドを削除
> alter table users drop column email score;
フィールドの型を変える
> alter table users change name user_name varchar(80);
テーブルの名前を変える
> alter table users rename persons;
全てのフィールドを抽出する
> select * from users;
特定のフィールドのみを抽出する
> select id, name from users;
条件付きでフィールドを抽出する
> select * from users where score >= 6;
=> score が6以上のすべてのフィールドを選択する
文字列を抽出条件にする
> select * from users where name = 'john';
部分一致で抽出
> select * from users where name like = 't%';
=> 先頭が t の値を抽出
> select * from users where name like = '%t%';
=> t を含む値を抽出
> select * from users where name like = 't%';
=> 末尾が t の値を抽出
文字数で抽出
> select * from users where name like = '_____';
=> 取得したい文字数分のアンダーバーを入れる
抽出結果の並び替え
> select * from users order by score asc;
=> 値を小さい順に並べる
> select * from user where score is not null order by score desc;
=> 値を大きい順に並べる且つ null を除外する
> select * from users limit 3;
=> 最初の3件のみ抽出
> select * from users limit 3 offset 3;
=> 最初の3件を飛ばして次の3件を抽出
> select * from users order by score desc limit 3;
=> 値を大きい順に3件抽出
レコードの更新
> update users set score = 5.9 where id = 1;
=> 1 の id を持つフィールドの値を更新
> update users set name = 'john', score = 2.9 where 'bob';
=> john の name を bob、score を 2.9 に更新
全てのデータの削除
> truncate table users;
外部ファイル読み込み
> \. ./create_other.sql