開発ノート【SQL文の基礎】
開発ノート【SQL文の基礎】です。
当サイトは、Bootstrap5で製作しています。
SQLの記述ルール
- 大文字・小文字は区別されない。
※全て小文字で書かれることが多い。 - 半角で書く。
- SQL文の最後にセミコロン(;)を付ける。
- 文字と日付はシングルクォーテーション(')で囲む。
- 単語は半角スペース又は改行で区切る。
SQL文の基礎
コメント文(コメントアウト)
- メモ書きとして利用する。
- 検証のため一時的に特定のSQLを無効にする。
構文
- --
- /* */
-
/*
*/
例
-- select * from users;
/* select * from users; */
/* select *
from users; */
select文
- データベースからデータを取得する。
構文
- select 列1,列2 ・・・ from テーブル名;
- select * from テーブル名;
例
use mysqldb;
select id,last_name from users;
select * from users;
where句
- 条件を指定して値を取得できる。
構文
- select 列1,列2 ・・・ from テーブル名 where 条件;
例
- select name,price from products where price >= 9800;
代表的な演算子
| 演算子 | 説明 |
|---|---|
| = | 等しい。 |
| > | より大きい。 |
| >= | 以上。 |
| < | より小さい。 |
| <= | 以下。 |
| <>,!= | 等しくない。 |
| in | ある値が値セット内に含まれているかどうか。 |
| not in | 値が値セット内に含まれていないかどうか。 |
| is null | 値がnull。 |
| is not null | 値がnullでない。 |
| like | パターンマッチング(あいまい検索)。 |
| between ... and ... | 値が値の範囲内に含まれているか。 |
limit句
- 取得件数を制限できる。
- 何件データが取得できるか試してみないとわからないときは、limit句を設定して1,000件位で様子をみるのが安全。(10万件/テーブルあたりからパフォーマンスが落ちてくる)
構文
- select 列1,列2 ・・・ from テーブル名 limit[オフセット,] 最大取得件数;
例
- 10件だけ取得する場合。
select * from products limit 10; - 10から5件取得するような場合。
select * from products limit 10,5;
like句
- パターンマッチングによる絞込ができる。
構文
- select 列1,列2 ・・・ from テーブル名 where 列名 like ワイルドカード文字;
例
- select * from users where last_name like '中%';
ワイルドカード文字
| ワイルドカード文字 | 説明 |
|---|---|
| '%' | 0文字以上の任意の文字列。
|
| '_' | 任意の1文字。 |
別名
- 列名に別名を付ける。
構文
- 列名の後に別名を書く。
※asは省略可。
例
- select name as 名前,price as 価格 from products;
- select name 名前,price 価格 from products;
列の値に対して演算
- 列の値に対して演算を行う。
例
- select name as 名前,price as 価格,price * 1.1 as 税込価格 from products;
集約関数による値の「集計」
-
集約関数
SQLでテーブルの値を集計できる。 - 集約関数において、nullは無視される。
主な集約関数
| 集約関数 | 説明 |
|---|---|
| sum(expr) | 合計値 |
| avg(expr) | 平均値 |
| min(expr) | 最小値 |
| max(expr) | 最大値 |
| count(expr) | 行数 |
| group by | データのグループ化 |
※expr(expression:式):引数のこと。
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集約関数
select avg(price) from products;
min集約関数
select min(price) from products;
max集約関数
select max(price) from products;
count集約関数
select count(*) from users where gender = 2;
count集約関数(ユニーク数を求める)
select
count(distinct user_id) /*重複削除*/
from
access_logs
where
request_month = '2017-01-01';
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;