技術とか戦略とか

IT技術者が技術や戦略について書くブログです。

Select文の結果を好きな順番に並び替える

既存データを使用してテストをする場合、特定の項目(社員番号や電話番号等、ソートキーになり得る項目)の順番にテストすることは少ないので、特定の項目でorder byするだけではテーブルのレコードをテスト順通りに並び替えられないことが多いです。

 
そこで、ソートキーを自分で作り、そのソートキーでorder byすることで、レコードをテスト順通りに並び替えることができます。
select文を順次unionで結合していけば新たにテーブルやカラムを定義する必要もありません。
また、結合する各々のselect文は、ソートキー(連番)とテストデータを一意に特定できるキー(テスト順)のみ変えれば良いので、Excelサクラエディタ等でselect文を作成するのも容易です。
 
具体的には、以下のように並び替えることができます。
 
・Select対象のテーブル
create table employee
(
employee_id CHAR(7) NOT NULL,
employee_name VARCHAR(20) NOT NULL,
salary DECIMAL(10),
PRIMARY KEY (employee_id)
);
insert into employee values("0000001","The President",20000000);
insert into employee values("0000002","The Director",10000000);
insert into employee values("0000003","The Manager",8000000);
insert into employee values("0000004","The Employee",6000000);
 
・select文
select 1 as sort_key ,e.* from employee e where employee_id = "0000001" union
select 2 as sort_key ,e.* from employee e where employee_id = "0000003" union
select 3 as sort_key ,e.* from employee e where employee_id = "0000002" union
select 4 as sort_key ,e.* from employee e where employee_id = "0000004"
order by sort_key;
 
・select結果
+----------+-------------+---------------+----------+
| sort_key | employee_id | employee_name | salary |
+----------+-------------+---------------+----------+
| 1 | 0000001 | The President | 20000000 |
| 2 | 0000003 | The Manager | 8000000 |
| 3 | 0000002 | The Director | 10000000 |
| 4 | 0000004 | The Employee | 6000000 |
+----------+-------------+---------------+----------+
4 rows in set (0.00 sec)