ORDER BY upper(...)与UNION给我带来问题

时间:2014-06-12 19:16:44

标签: sql oracle sql-order-by oracle-sqldeveloper union-all

我在弄清楚为什么遇到这个问题时遇到了一些麻烦。

此代码的确如此工作。它结合了两个表(MESSAGES和MESSAGES_ARCHIVE)并正确排序。

SELECT * FROM ( 
    SELECT rownum as rn, a.* FROM ( 
        SELECT  
        outbound.FROM_ADDR, outbound.TO_ADDR, outbound.EMAIL_SUBJECT

        from MESSAGES outbound 
        where (1 = 1) 

        UNION ALL

        SELECT  
        outboundarch.FROM_ADDR, outboundarch.TO_ADDR, outboundarch.EMAIL_SUBJECT

        from MESSAGES_ARCHIVE outboundarch 
        where (1 = 1)  

        order by FROM_ADDR DESC 
    ) a 
) where rn between 1 and 25

但是,此代码不起作用。

SELECT * FROM ( 
    SELECT rownum as rn, a.* FROM ( 
        SELECT  
        outbound.FROM_ADDR, outbound.TO_ADDR, outbound.EMAIL_SUBJECT

        from MESSAGES outbound 
        where (1 = 1) 

        UNION ALL

        SELECT  
        outboundarch.FROM_ADDR, outboundarch.TO_ADDR, outboundarch.EMAIL_SUBJECT

        from MESSAGES_ARCHIVE outboundarch 
        where (1 = 1)  

        order by upper(FROM_ADDR) DESC 
    ) a 
) where rn between 1 and 25

并返回此错误

ORA-01785: ORDER BY item must be the number of a SELECT-list expression
01785. 00000 -  "ORDER BY item must be the number of a SELECT-list expression"

我试图让两张桌子排序,不管是不是字母大小写,这就是我使用upper(FROM_ADDR)的原因。有什么建议?谢谢!

2 个答案:

答案 0 :(得分:1)

我不太确定为什么会产生错误,但它可能与union查询的范围规则有关。使用row_number()

可以轻松解决问题
SELECT * FROM ( 
    SELECT row_number() over (order by upper(FROM_ADDR)) as rn, a.*
    FROM ( 
        SELECT  
        outbound.FROM_ADDR, outbound.TO_ADDR, outbound.EMAIL_SUBJECT

        from MESSAGES outbound 
        where (1 = 1) 

        UNION ALL

        SELECT  
        outboundarch.FROM_ADDR, outboundarch.TO_ADDR, outboundarch.EMAIL_SUBJECT

        from MESSAGES_ARCHIVE outboundarch 
        where (1 = 1)  

    ) a 
)
where rn between 1 and 25

答案 1 :(得分:0)

您的upper()返回一个值,但不是列名。 而不是:

order by upper(FROM_ADDR) DESC

尝试:

order by upper(FROM_ADDR) as FROM_ADDR DESC