查询单个表作为主数据和明细,并对结果进行排序,其中主行将位于每个明细的顶部

时间:2019-02-27 18:46:07

标签: mysql sql row

可以做到吗?请帮助我。

我尝试了联合,只是它没有按照我想要的方式排序-主行位于明细行的顶部。谢谢你。

SELECT 
mover.v_id, 
mover.v_registration, 
mover.attached_with       
from ops_vehicle mover
LEFT JOIN v_l_type ON (mover.type = v_l_type.idv_type)
where v_l_type.trailer = FALSE       
union all
SELECT 
trailer.v_id, 
trailer.v_registration, 
trailer.attached_with
from ops_vehicle trailer
LEFT JOIN v_l_type ON (trailer.type = v_l_type.idv_type)
where v_l_type.trailer = TRUE

结果: query result

我想要的结果是这样的:

v_id      v_registration      attached_with
-------------------------------------------
1         ABC 123             4
4         T/B 123
2         CBA 876             5
5         T/B 763
3         OPQ 631

v_id = 4的结果行应位于v_id = 1下,因为attach_with为4。

1 个答案:

答案 0 :(得分:0)

是的,您可以这样做:

select t.*
from (<your query here>) t
order by coalesce(attached_with, v_id),
         (attached_with is not null) desc,
         v_id