select文
select 列1, 列2, … from テーブル名;
全ての列を取得したい場合
select * from テーブル名;
列に別名をつける
select name as 名前, price as 価格 from テーブル名;
※asは省略可能
列の値の演算
例)
select
name as 名前,
prce as 価格,
price * 1.1 as 税込価格
from
products;
where句
select 列1, 列2, … from テーブル名 where 条件;
例)
select
name,
price
from
products
where
price >= 9800;
like句 ~みたいな
select
列1,
…
from
テーブル名
like
ワイルドカード文字;
ワイルドカード文字
% ・・・ 0文字以上の任意の文字列
_ ・・・ 任意の1文字
limit句 最大表示件数
select
列1,
…
from
テーブル名
limit
[オフセット,]
最大取得件数;
※オフセット ・・・ 件数○件目から~
検索結果の合計を表示(sum関数)
例)
select
sum(amount)
from
orders
where
order_time >= ‘2017-01-01 00:00:00’
and order_time < ‘2017-02-01 00:00:00’;
その他代表的な関数
avg ・・・ 平均
min ・・・ 最小値
max ・・・ 最大値
count ・・・ 対象の行数を数える
abs ・・・ 絶対値
round ・・・ 四捨五入(オプション(,以下)で桁数指定
月間ユニークユーザー数を求める
例)
select
count(distinct user_id)
from
access_logs
where
request_month = ‘2017-01-01’;
※distinct ・・・ 重複をまとめる
group by句
select
列名
from
テーブル名
group by
列名;
例) 都道府県別ユーザー数みたいな
select
prefecture_id,
count(*)
from
users
group by
prefecture_id;
例) 月間ユニークユーザー数みたいな
select
request_month,
count(distinct user_id)
from
access_logs
where
request_month >= ‘2017-01-01’
and request_month < ‘2018-01-01’
group by
request_month;
having句 さらに絞り込む
例) 月間ユニークユーザー数630人以上の月みたいな
select
request_month,
count(distinct user_id)
from
access_logs
where
request_month >= ‘2017-01-01’
and request_month < ‘2018-01-01’
group by
request_month
having
count(distinct user_id) >= 630;
構文の順番
select
列1, …
from
テーブル名
結合処理
where
条件式
group by
列1, …
having
条件式;
order by
列名または式,
limit
order by句 データの並び替え
補足:並び替え
asc ・・・ 昇順(指定しないでも大丈夫)
desc ・・・ 降順
文字列演算
a || b ・・・ 文字列aと文字列bを連結
concat ・・・ concat(文字列1, 文字列2)でも同じ
inner join
内部結合→null列の表示なしjoinだけでも可
例) id同士を結合してテーブルを結合する
select
u.id,
u.last_name,
u.first_name,
p.name
from
users u
inner join
prefectures p
on u.prefecture_id = p.id
inner join + where
select
テーブル名1.列名
テーブル名2.列名
from
テーブル名1
inner join
テーブル名2
on テーブル名1.列名 = テーブル名2.列名
where
絞り込み条件;
left outer join
外部結合nullも表示
left outer join
・・・左側(from句で最初に書いたテーブル)をマスタとする
right outer join\
・・・右側(from句で後に書いたテーブル)をマスタとする
3つ以上のテーブル結合
例)
select
*
from
orders o
inner join
order_details od
on o.id = od.order_id
inner join
products p
on od.product_id = p.id
innner join
users u
on o,user_id = u.id;
テーブルの足し算 union
select
列1,
…
from
テーブル1
union select
列2,
…
from
テーブル2
※列を合わせる必要がある
ビューの作成
よく使うSQLの保存
例)
create view ビューの名前(列1,列2)
as
サブクエリ
select
列名,…
from
テーブル名
where
列名 演算子 ( select 列名 from テーブル名2 …);
※in または not in を使ったりする
|
|
|
|---|


コメント