所以我在MariaDB数据库中有一个表,其中有几行,如:
+----+--------+-----------+---------+-----------+
| id | faseID | fase_tipo | fase_nr | tarefa_id |
+----+--------+-----------+---------+-----------+
| 5 | 3 | 2 | 1 | 2 |
| 6 | 3 | 2 | 2 | 2 |
| 17 | 3 | 2 | 3 | 2 |
| 12 | 3 | 3 | 1 | 6 |
| 18 | 3 | 3 | 2 | 6 |
+----+--------+-----------+---------+-----------+
生成者:
SELECT id,
faseID,
fase_tipo,
fase_nr,
tarefa_id
FROM tarefas
WHERE obra = '15ID000' AND
faseID = '3' AND
tarefa_id <> '0' AND
tarefa_main = '2'
ORDER BY fase_tipo ASC
我在订购此搜索结果时遇到问题,因为我希望将表格排序为:
+----+--------+-----------+---------+-----------+
| id | faseID | fase_tipo | fase_nr | tarefa_id |
+----+--------+-----------+---------+-----------+
| 5 | 3 | 2 | 1 | 2 |
| 6 | 3 | 2 | 2 | 2 |
| 12 | 3 | 3 | 1 | 6 |
| 18 | 3 | 3 | 2 | 6 |
| 17 | 3 | 2 | 3 | 2 |
+----+--------+-----------+---------+-----------+
我的意思是,使用字段tarefa_id
使行显示在id
行之后。在内部,它与fase_nr
订购。
是否有任何定位tarefa_id
= id
之后显示tarefa_id
的所有行?
答案 0 :(得分:1)
看看下面的内容,它应该通过自我加入和coalesce
功能为您提供所需的内容。
with test_data as (
select 5 as id, 3 as faseID, 2 as fase_tipo, 1 as fase_nr, 2 as tarefa_id from dual
union all
select 6 as id, 3 as faseID, 2 as fase_tipo, 2 as fase_nr, 2 as tarefa_id from dual
union all
select 12 as id, 3 as faseID, 3 as fase_tipo, 1 as fase_nr, 6 as tarefa_id from dual
union all
select 18 as id, 3 as faseID, 3 as fase_tipo, 2 as fase_nr, 6 as tarefa_id from dual
union all
select 17 as id, 3 as faseID, 2 as fase_tipo, 3 as fase_nr, 2 as tarefa_id from dual
)
-- This is the core you should pay attention to
select td1.*
from test_data td1
left join test_data td2
on td2.id = td1.tarefa_id
order by coalesce(td2.id, td1.id), td1.id, td1.fase_nr
--
;
当然,我在Oracle中做过这个,但总体思路应该适用。
输出:
ID|FASEID|FASE_TIPO|FASE_NR|TAREFA_ID
--+------+---------+-------+---------
5| 3| 2| 1| 2
6| 3| 2| 2| 2
12| 3| 3| 1| 6
18| 3| 3| 2| 6
17| 3| 2| 3| 2
如果您的列不是数字类型,则需要在order by
子句中对其进行转换以进行排序:
with test_data as (
select '12' as id, '3' as faseID, '3' as fase_tipo, '1' as fase_nr, '6' as tarefa_id from dual
union all
select '5' as id, '3' as faseID, '2' as fase_tipo, '1' as fase_nr, '2' as tarefa_id from dual
union all
select '18' as id, '3' as faseID, '3' as fase_tipo, '2' as fase_nr, '6' as tarefa_id from dual
union all
select '6' as id, '3' as faseID, '2' as fase_tipo, '2' as fase_nr, '2' as tarefa_id from dual
union all
select '17' as id, '3' as faseID, '2' as fase_tipo, '3' as fase_nr, '2' as tarefa_id from dual
)
-- This is the core you should pay attention to
select td1.*
from test_data td1
left join test_data td2
on td2.id = td1.tarefa_id
order by to_number(coalesce(td2.id, td1.id)), to_number(td1.id), to_number(td1.fase_nr)
--
;