gotagota日記

「面白きことは良きことなり」

MySQLについて

MySQLについてドットインストールで学習したので自分用にメモ。

MySQLログイン

# mysql -u root -p

データベース作成

create database [データベース名];

データベース削除

drop database [データベース名];

データベース一覧表示

show databases;

データベース切り替え

use [データベース名];

作業ユーザー設定

grant all on [データベース名].* to [作業ユーザー名]@localhost identified by ‘[任意のパスワード]’

作成した作業ユーザーでログイン

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

テーブルを作る
create table [テーブル名] (  
  [フィールド名] [データの型],  
  [フィールド名] [データの型],  
  [フィールド名] [データの型],  
  ・  
  ・  
  ・  
);  
dot installの例
create table users (  
  id int,  
  name varchar(255),  
  email varchar(255),  
  password char(32)  
);  

int → 整数
varchar() → 文字数制限

◆ 扱えるデータ型

数値

  • int
  • double

文字列

  • char
  • varchar
  • text

日付

  • date
  • datetime

それ以外

◆ 使えるオプション

入力必須

  • not null

デフォルト値を設定

  • default

自動連番

  • auto_increment

索引

  • 主キー primary key
  • キー key [フィールド名]
  • ユニークキー unique テーブルの中で重複したものがきたらエラーで弾く
レコードの挿入

insert into [テーブル名] () values ();

レコードの抽出

select * from [テーブル名];

条件付きでの抽出

select * from [テーブル名] where 条件;

並べ替え 正順

select * from [テーブル名] order by [フィールド名];

並べ替え 逆順

select * from [テーブル名] order by [フィールド名] desc;

件数を調べる

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

重複なしでユニークな値だけ引っ張る

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

最大値をとる

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

◆ レコードの更新、削除

update [テーブル名] set [フィールド名] = ‘値’ where 条件

delete from [テーブル名] where 条件

◆ テーブルの構造変更

-付け加える
alter table [テーブル名] add [付け加えたいフィールド名] [レコードの条件] [場所の条件]
-消す
alter table [テーブル名] drop [消したいフィールド名]