dw90000
11/27/2014 - 9:08 AM

MySQL 操作メモ

MySQL 操作メモ

MySQL基本

手動でサーバー起動・停止

$ mysql.server start
$ mysql.server stop

rootユーザのパスワードの設定

$ mysqladmin -u root password [パスワード] mysql> SET PASSWORD FOR root@localhost=PASSWORD(‘[パスワード]’);

ルートでログイン

mysql -u mysql root -p

ユーザーでデータベースを指定してログイン

mysql -u [ユーザー名] -p [データベース名]

基本操作

データベース作成

create database [データベース名]

データベース一覧

show databases

データベース一覧

use [データベース名]

データベース削除

drop [データベース名]

ユーザー追加

(データベースを選択した状態で)

grant all on blog_app.* to [ユーザ名]@localhost identified by '[パスワード]';

テーブル作成

create table [テーブル名] ( [フィールド] );

テーブル一覧

show tables

テーブルの削除

drop table [テーブル名]

データ型

数値型

  • int
  • double

文字列型

  • char (固定長)
  • varchar (可変長)
  • text

日付・時間

  • date
  • datetime

その他

  • enum (列挙型)

例:

create table users (
  id int,
  name varchar(255),
  email varchar(255),
  password char(32),
  score double,
  sex enum('male','female'),
  memo text,
  created datetime
);

オプション

  • 入力を必須 -> not null
  • デフォルト値 -> default 'hoge'
  • 自動連番 -> auto_increment
    ※auto_increment を指定したフィールドには必ずインデックスを指定

*索引(インデックス)

  • 主キー -> primary key
  • キー -> key
  • ユニークキー -> unique

例:

create table users (
  id int not null auto_increment primary key,
  name varchar(255),
  email varchar(255) unique,
  password char(32),
  score double,
  sex enum('male','female') default 'male',
  memo text,
  created datetime,
  key score (score)
);

テーブルの構造を確認

desc [テーブル名]

レコード挿入

例:

insert into users (name,email,password,score,memo,created) values ('taro','taro@gmail.com','xxx','5.5','memomemomemo','2012-06-12 11:00:00');

レコードの確認

select [フィールド名] from [テーブル名]

// すべて
select * from [テーブル名]

// 縦に表示
select [フィールド名] from [テーブル名] \G

// where句
select * from users where [フィールド名] [比較演算子] [値/]

// like あいまい検索

% 
select * from users where [フィールド名] like [%+検索ワード]

_ 任意の文字数
select * from users where [フィールド名] like [検索ワード+___]

// between 数値?指定の間のレコードを抽出する
select * from users where [フィールド名] between [数値] and [数値]

// in 複数のレコードのどれかが含まれれる場合
select * from users where [フィールド名] in ('[値]','[値]');

// order by
select * from users order by [フィールド名]
select * from users order by [フィールド名] desc

// limit
select * from users order by [フィールド名] limit [数字]
オフセットも可能
select * from users order by [フィールド名] limit [オフセット] , [数字]


whereは and or で複数条件を足すことが出来る。

データの集計

レコードの総件数

select count(*) from [テーブル名];

どんな値が入っているのか

select distinct [フィールド名] from [テーブル名];

最大値

select max([フィールド名]) from [テーブル名];

他にも最小値 min 平均 avg 合計 sumがある

グループごとに集計

select avg([フィールド名]) from [テーブル名] group by [フィールド名];

ランダムで一つだけ抽出する

select * from [テーブル名] order by rand() limit 1;