■文字コードを指定してtableを作成する
create table tbname(bang varchar(10),name varchar(10),age int) charset=sjis;
■ソースの履歴を表示する
「↑」「↓」「F7(履歴一覧)」
■tableをコピー
create table tb2 select * from tb1;
■指数表現
「○E+△」は「○*10の△乗」
一万は「1E+4」
■日付・時刻型
【DATETIME】 YYYY-MM-DD HH:MM:SS
【DATE】 YYYY-MM-DD
データは必ず""または''で囲む
■処理実行日時
insert into テーブル名(カラム名) values(now());
■カラム構造の変更
カラムの定義変更: alter table テーブル名 modify カラム名 データ型;
カラムの追加: alter table テーブル名 add カラム名 データ型;
カラムの名前と定義変更: alter table テーブル名 change カラム名 データ型;
カラムの削除: alter table テーブル名 drop カラム名 データ型;
■一意のカラム
auto にしなくても primary key だけ設定しておけば重複を弾く
create table tbname(id int primary key,name varchare(10));
■デフォルト値を設定
alter table tbname modify name varchar(10) default '氏名未入力';
■¥Gでカラムごとに表示
命令最後の;の代わりに¥Gを入力するとカラムごとに見やすく表示してくれる。status等に。
■レコードの全削除
テーブルは削除せずにレコードを全削除
delete from テーブル名;
■カラムの値を計算して表示
select price*1000 as 価格 from tablename;
select avg(price) as 平均価格 from tablename;
■DBの現状を表示
Mysqlサーバーのバージョン:select version();
現在のDB:select database();
現在のユーザー:select user();
引数で指定した文字の文字コード:select charset('この文字なぁに?');
■文字を結合
select contact(カラム名1,カラム名2,'億円') from tb1;
■数値の条件を指定して抽出
レコード数を限定:select * from tablename limit 10;
条件を限定:select * from tablename where age>=20;
除外条件を設定:select * from tablename where age<>20;
条件範囲を設定:select * from tablename where between 20 and 80;
除外範囲を設定:select * from tablename where not between 40 and 80;
条件を限定(複数);select * from tablename where age in (20,21);
■文字列の条件を指定して抽出
select * from tabelname where name = '佐藤';
select * from tabelname where name like = '佐%';
■複雑な抽出
selsect * from tabelname where name like = '佐%' and age=20 or term>=10;
■条件によって値を変更して表示
select id,price,
case
when price>=10000 then '高い'
when price>=5000 then '検討'
else '即買い'
end as 評価
from tablename;
■並替え
安いものから(ASCは省略可)3件表示
select * from tablename order by price ASC limit 3;
高いものから(DESC)5件削除
delete * from tablename order by price DESC limit 3;
■グループ化
同じ名前のレコードが複数あった場合、それを名前でユニークにする(複数の中から勝手に選ばれたレコードが表示される)
select * from tablename group by name;
名前ごとに、何件レコードがあるかカウントして表示する
select name,count(*) as 件数 from tablename group by name;
同様に合計:select name,sum(price) as 合計 from tablename group by name;
同様に平均:select name,avg(price) as 合計 from tablename group by name;
更に条件をつける
select name,avg(price) as 合計 from tablename group by name having avg(price)>=1000;
■条件に一致したレコードのカラムを修正
update tablename set hyouka='長身3人組' order by tall limit 3;
■条件にあったレコードをコピー
create table satousan select * from tbname where name='佐藤';