MySQL 操作メモ
MySQL基本
$ mysql.server start
$ mysql.server stop
$ 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 [テーブル名]
数値型
文字列型
日付・時間
その他
例:
create table users (
id int,
name varchar(255),
email varchar(255),
password char(32),
score double,
sex enum('male','female'),
memo text,
created datetime
);
*索引(インデックス)
例:
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;