LoginSignup
2
2

More than 5 years have passed since last update.

SQLの基本操作覚え書き

Last updated at Posted at 2016-07-27

ドットインストールのMySQL入門で覚えたコマンドのメモ。文法確認用に。

データベースhoge内のfugaテーブルにidフィールドとnameフィールドを作成して、レコードを挿入していく。

データベース操作

データベース一覧

$ show databases;

作成

$ create database hoge;

ユーザの権限設定(user:Tarouがdatabase:hogeを編集できるようにする)

$ grant all on hoge.* to Tarou@localhost identified by "passwd";

削除

$ drop database hoge;

使用するDBの指定

$ use hoge;

DB(hoge)についてユーザ(user)の指定

$ grant all on hoge. * to user@localhost identified by "passwd";

バックアップ用のダンプファイル作成

$ mysqldump -u root データベース名 > ダンプファイル名.sql

ダンプファイルからの復元

$ mysql -u root データベース名 < ダンプファイル名.sql

テーブル・フィールド操作

テーブル一覧

$ show tables;

特定テーブルの情報

$ desc fuga;

削除

$ drop table fuga;

作成

$ create table fuga(
 id int;
 name varchar(32),
 ...
 );

フィールドのオプション

  • not null
  • default
  • auto_increment

  • キーの指定

    • primary key(主キー)
    • key(キー)
    • unique(ユニークキー)
  • index(indexを付けたフィールドは、そのフィールドでの検索時に動作が速くなるが、あまり多くのフィールドに付けると動作が重くなる)

  • references(外部キー)

変更(オプションの追加やフィールド名の変更等)

ex.) テーブル名の変更
$ alter table fuga rename fugafuga;
ex.2) fugaテーブルのidフィールドにnot null制約を追加
$ alter table fuga modify id int not null;
ex.3) fugaテーブルのidフィールドをuser_idフィールドと名前変更
$ alter table fuga change id user_id int;

インデックスの追加, 削除

alter table テーブル名 add index インデックス名(カラム名);
alter table テーブル名 drop index インデックス名;

レコード操作

レコード一覧

$ select * from fuga;

レコードの特定フィールド(name)の参照

$ select name from hoge;

レコード一覧の縦表示

$ select * from hoge \G #セミコロンは不要

挿入

$ insert into fuga (id, name) values (999999, "Jane Doe");

削除

$ delete from fuga where name = "Jane Doe"

更新

$ update fuga set name = "Tanaka Tarou" where name = "Jane Doe"

条件抽出(where)

ex.) nameが"Jane Doe"のレコードを抽出
$ select * from fuga where name = "Jane Doe"; #等号は"=="ではないので注意

ex.2) nameにDを含むレコードを検索
$ select * from fuga where name like "%D%"; # %は0文字以上の任意の文字列

ソート

$ select * from fuga order by ~~ # 末尾に"desc"で降順

グルーピングと集計

ex.)studentsテーブルにおいてtest_scoreの平均点をclassごとに集計する
$ select avg(test_score) from students group by class

忘れがちな小技

ランダムにn件抽出

乱数生成のrand()とlimitを利用
$ select * from fuga order by rand() limit 1

フィールドの型だけを変更(nameをvarchar(32) -> varchar(64))

$ alter table fuga change name name varchar(64)

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2