LoginSignup
21
11

More than 5 years have passed since last update.

select文で order by 、 group by に選択列番号を指定する

Last updated at Posted at 2014-08-30

以下のようなテーブルがあるとする。

create table a (id serial, name text);

以下のように選択列番号を指定して order by を記載すると、name の昇順で取得することが出来る。
選択列番号とは select から from の間に書いたカラムを1オリジンで数字を割り当てたもの。

select id, name from a order by 2;

なお select * を指定したときは、テーブルに定義された順にカラムが指定されたものとして動く。

これは group by にも使うことが出来る。
以下は同じ長さの name のものがそれぞれ何件ずつあるかを多い順に出力する。

select length(name), count(*) from a group by 1 order by 2 desc;

ちなみにMySQLのサイトには、「選択列番号の指定はSQL標準から外れたから今後廃止されるかも」と書いてあったが気にしない。

21
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
11