按日期格式在mysql中使用union

时间:2015-05-15 04:43:25

标签: mysql mysql-workbench

我使用了order with order,在结果表中,日期格式不是订购。

(
    select 
        DATE_FORMAT(Date_1, '%m/%d/%Y') as  first_date, 
        null as second_date,
        col_2,
        Col_3,
        col_4 from table1 where Date_1 !=''
)
union all
(
    select 
        null as first_date , 
        DATE_FORMAT(Date_2, '%m/%d/%Y') as second_date, 
        col_2, 
        null as col_3, 
        col_4
    from table1 
    where Date_2 !=''
)
order by  Date_1 desc, Date_2 desc;   

以上我能够检索记录但不订购日期。任何帮助!

1 个答案:

答案 0 :(得分:1)

摘自MySQL reference

  

如果要排序的列是别名,则ORDER BY子句必须引用   别名,而不是列名。

    (
        select 
            DATE_FORMAT(Date_1, '%m/%d/%Y') as  first_date, 
            null as second_date,
            col_2,
            Col_3,
            col_4 from table1 where Date_1 !=''
    )
    union all
    (
        select 
            null as first_date , 
            DATE_FORMAT(Date_2, '%m/%d/%Y') as second_date, 
            col_2, 
            null as col_3, 
            col_4
        from table1 
        where Date_2 !=''
    )
    order by  first_date  desc, second_date desc;