用途
SQLで重複しているものは表示させたくない時に使う。
DISTINCTの使用方法
書き方
SELECT DISTINCT 指定するカラム名, 指定するカラム名, ... FROM テーブル名 ;
使用するhogeテーブル
| name | color | number |
|---|---|---|
| suzuki | red | 10 |
| suzuki | red | 10 |
| takahashi | blue | 10 |
DISTINCT無しの場合
DISTINCT無し
SELECT number from hoge;
結果
| number |
|---|
| 10 |
| 10 |
| 10 |
DISTINCTありの場合
DISTINCTあり
SELECT DISTINCT number from hoge;
結果
| number |
|---|
| 10 |
※numberカラムで重複しているものを削除して表示される。
DISTINCT無しでカラム指定が複数の場合
DISTINCT無しでカラム指定が複数
SELECT color, number from hoge;
結果
| color | number |
|---|---|
| red | 10 |
| red | 10 |
| blue | 10 |
DISTINCTありでカラム指定が複数の場合
DISTINCT無しでカラム指定が複数
SELECT DISTINCT color, number from hoge;
結果
| color | number |
|---|---|
| red | 10 |
| blue | 10 |
※ colorカラム と numberカラム の両方が重複しているものを削除して表示される。