9
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

MySQL 文字を含む数値列を数値順に並び替える

Posted at

概要

困っている人がいたので助けたいなと思いました。

テーブル

CREATE TABLE company (
  company_code VARCHAR(255)
);

INSERT INTO company
VALUES
  ('C1')
  , ('C10')
  , ('C100')
  , ('C12')
  , ('C13')
;

並び替える

SELECT company_code FROM company ORDER BY company_code;

C1
C10
C100
C12
C13

普通に並び替えすると文字列として並び替えてしまいます。

数値として並び替える

SELECT company_code FROM company ORDER BY LENGTH(company_code), company_code;

C1
C10
C12
C13
C100

数値として並び替えてくれます。
LENGTH 関数を使って、まずは文字数で並び替えてあげると上手くいきます。

参考

9
2
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
9
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?