MariaDB
version: 10.2.11
ログイン
ログイン
$ mysql -u ユーザ名 -p
password:パスワードを入力
ログアウト
quit;
ログイン中のユーザ名取得
select user();
コマンドヘルプ
help コマンド名;
コメント
# ラインコメント
-- ラインコメント
/*
ブロックコメント
*/
ユーザ管理
ユーザ一覧
select * from mysql.user;
ユーザ作成
create user ユーザ名@ホスト名;
create user ユーザ名@ホスト名 identified by 'パスワード';
パスワード設定
set password for ユーザ名@ホスト名 = password('パスワード');
ユーザ作成情報取得
show craete user ユーザ名@ホスト名;
権限設定
grant 権限 on データベース名.テーブル名 to ユーザ名@ホスト名;
# example:user1にhogeデータベース全テーブルに対する閲覧操作権限を付与
grant all privileges on hoge.* to user1;
権限
all, all privileges # 全権限を付与
usage # 権限無し
# ユーザ権限
create user, shutdown, super
# データベース、テーブル権限
create, create view, alter, drop
show databases, show view
# データ権限
select, insert, delete, drop, alter
権限確認
# 現在のユーザの権限
show grants;
# 指定したユーザの権限
show grants ユーザ名@ホスト名;
データベース管理
データベース一覧
show databases;
データベース作成
create database データベース名;
データベース選択
use データベース名;
データベース削除
drop database データベース名;
テーブル管理
テーブル一覧
show tables;
テーブル作成
create table テーブル名 (
カラム名 型名 オプション,
...
);
型名
# 整数
tinyint, smallint, mediumint, int, integer, bigint,
# 固定小数点数
decimal, dec, numeric, fixed
# 浮動小数点数
float, double
# 文字列
char, varchar, text, tinytext mediumtext, longtext,json data type, enum
# バイナリ
binary, char byte, varbinary
# BLOB
blob, tinyblob, mediumblob, longblob
# 日時
date, time, datetime, timestamp, year data type
オプション
null # null値を許す
not null # null値を許さない
default デフォルト値 # データ作成時のデフォルト値
auto_increment # 自動採番
unique # 値の重複を許さない
key # キーとして設定
primary key # 主キーとして設定
comment 'コメント' # このカラムの説明とか
テーブル情報取得
desc テーブル名;
テーブル削除
drop table テーブル名;
データ操作
取得・挿入・更新・削除
データ取得
select カラム名 from テーブル名;
select カラム名 from テーブル名 where 条件;
select カラム名 from テーブル名 order by カラム名;
select カラム名 from テーブル名 group by カラム名;
データ挿入
insert テーブル名 values (値, ...);
insert テーブル名 (カラム名, ...) values (値, ...);
insert テーブル名 (カラム名, ...) values (値, ...),(値, ...), ...;
データ更新
update テーブル名 set カラム名=値, ... where 条件;
update テーブル名 set カラム名=値, ... order by カラム名 limit 更新数;
# 悪夢のコマンド
update テーブル名 set カラム名=値, ...;
データ削除
delete from テーブル名 where 条件;
delete from テーブル名 order by カラム名 limit 削除数;
# 悪夢のコマンド
delete from テーブル名;
where 句
値比較
where カラム名 = 値 # 一致
where カラム名 <> 値 # 不一致
where カラム名 < 値
where カラム名 <= 値
where カラム名 > 値
where カラム名 >= 値
betweenキーワード
where カラム名 between 下限値 and 上限値
where カラム名 >= 下限値 and カラム名 <= 上限値 と同義
INキーワード
where カラム名 in (値1, 値2);
where カラム名 = 値1 or カラム名 = 値2 と同義
ワイルドカード
%hoge # 任意の文字列+hoge
_hoge # 任意の一文字+hoge
LIKEキーワード
where カラム名 like '%hoge%';
where カラム名 like '_hoge_';
NULLフィールド検索
where カラム名 is null;
where カラム名 is not null;
having 句
order by 句
データをソート
order by カラム名 # 指定したカラムの値を昇順で並び替え
order by カラム名 asc # 昇順で並び替え
order by カラム名 desc # 降順で並び替え
group by 句
同じ値のデータをグルーピング
group by カラム名
おまけ
DBサーバの状態確認
status;
設定一覧
show status;