---
title: "在union all中使用order by 报错的解决方案"
author: "wangyanlong0107"
date: "2012-08-06T17:40:22Z"
tags: []
categories: ["数据库"]
slug: "union-all-order-by"
draft: false
lastmod: "2012-08-06T17:40:38Z"
id: 1622484
url: "https://bigdragon.iteye.com/blog/1622484"
---

//解法一:     
select * from (       
       select col\_1,col\_2,col\_3,status       
       from t       
       where status &gt;= 0       
       order by status)       
union all       
select * from (       
       select col\_1,col\_2,col\_3,status       
       from t       
       where status &lt; 0       
       order by status)       
/       
COL\_1  COL\_2   COL\_3      STATUS       
\------ ------- ------ ----------       
花生   瓜子    绿豆            0       
芍药   牡丹    月季            1       
优乐美 香飘飘  炸鸡            2       
牙膏   牙刷    杯子            3       
china  america canada         -1      
//解法二:     
select * from t      
order by      
      decode(status,     
             -1,1,     
             3,2,     
             2,3,     
             1,4,     
             0,5) desc     
/     
//这可是一个很妙的排序，本人首次看到在order by语句中可以使用decode()函数来排序     
//同理，我们也可以使用case语句来排序:     
//解法三:     
select * from t      
order by      
      case status     
      when -1 then 5     
      when 3 then 4      
      when 2 then 3      
      when 1 then 2      
      else 1     
      end      
/     
//union 和union all中都支持order by和group by排序和分组子句