その他

MySQL

kurumin

基本の基本

SQLの中に入る。

// パスワードがない場合
mysql -u root 
// パスワードがある場合
mysql -u root -p

データベース一覧を表示。

show databases;

データベースに入る。

use データベースの名前;

テーブル一覧を表示。

show tables;

テーブルの情報を確認。

// どのような定義で作られているか
desc テーブルの名前;
// テーブルの中身を表示
select * from テーブルの名前;

テーブル操作

userテーブルのnameの後に、kanaというフィールドを追加。

alter table user add kana varchar(100) after name;

フィールドの定義を変更。

alter table user change kana kana varchar(255);

フィールドを削除。

alter table user drop kana;

テーブルの名前変更。

alter table user rename customer;

作成したテーブルがどういう命令文で作られているか確認。

show create table user;

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

よく使用するレコードをインデックスに追加することで、検索スピードの向上ができる。

インデックスの追加。

alter table user add index email(id,email);

インデックスの削除。

alter table user drop index email;

集計

データの件数を取得。

select count(id) from item;

合計値を計算。

select sum(price) from item;

平均値を計算。

select avg(price) from item;

一番値が大きいものを表示。

select max(price) from item;

一番値が小さいものを表示。

select min(price) from item;

グループ集計。

// purchase_historyテーブルのuser_idごとにidの数を表示。
select user_id, count(id) from purchase_history group by user_id;

複数のテーブルから検索

INNER JOIN(内部結合)

互いの条件に一致する(存在する)レコードのみを抽出。

// userテーブル(id)とpurchase_historyテーブル(user_id)が一致するレコードを結合して表示。
select * from user inner join purchase_history on user.id = purchase_history.user_id;

LEFT JOIN

左のテーブル(userテーブル)のデータを残して結合。

select * from user left join purchase_history on user.id = purchase_history.user_id;

RIGHT JOIN

右のテーブル(purchase_historyテーブル)のデータを残して結合。

select * from user right join purchase_history on user.id = purchase_history.user_id;

応用

select user.name,item.price,item.name from user left join purchase_history on user.id=purchase_history.user_id left join item on purchase_history.item_id=item.id;
ABOUT ME
記事URLをコピーしました