假设我的condition
表格中包含以下列:
+----+----------+-----------+
| ID | Name | Condition |
+----+----------+-----------+
| 1 | Value 1 | NULL |
| 4 | Value 2 | NULL |
| 13 | Value 3 | NULL |
| 8 | Value 4 | 1 |
| 10 | Value 5 | 1 |
| 12 | Value 6 | 1 |
| 17 | Value 7 | 1 |
| 18 | Value 8 | 1 |
| 20 | Value 9 | 1 |
| 21 | Value 10 | 1 |
| 6 | Value 11 | 4 |
| 11 | Value 12 | 4 |
| 16 | Value 13 | 4 |
| 14 | Value 14 | 13 |
| 19 | Value 15 | 13 |
+----+----------+-----------+
现在,我希望他们订购ID
和Condition
按顺序逐个排序:
+----+----------+-----------+
| ID | Name | Condition |
+----+----------+-----------+
| 1 | Value 1 | NULL |
| 8 | Value 4 | 1 |
| 10 | Value 5 | 1 |
| 12 | Value 6 | 1 |
| 17 | Value 7 | 1 |
| 18 | Value 8 | 1 |
| 20 | Value 9 | 1 |
| 21 | Value 10 | 1 |
| 4 | Value 2 | NULL |
| 6 | Value 11 | 4 |
| 11 | Value 12 | 4 |
| 16 | Value 13 | 4 |
| 13 | Value 13 | NULL |
| 14 | Value 14 | 13 |
| 19 | Value 15 | 13 |
+----+----------+-----------+
我该怎么做?
答案 0 :(得分:0)
这是一个奇怪的排序顺序。因此,Condition
中不存在ID的记录应先由Condition
然后ID
排序,而Condition
中包含ID的记录应按ID
排序在Condition
中具有该ID的记录之前。一种方法是使用上面提到的sortkeys选择这两个集合,并在两个集合上使用union all
。
select id, name, condition
from
(
select
id,
name,
condition,
id as sortkey1,
1 as sortkey2,
null as sortkey3
from mytable
where id in (select condition from mytable)
union all
select
id,
name,
condition,
condition as sortkey1,
2 as sortkey2,
id as sortkey3
from mytable
where id not in (select condition from mytable)
)
order by sortkey1, sortkey2, sortkey3;