代码之家  ›  专栏  ›  技术社区  ›  Ram Singh

Order by不能与Union ALL my sql一起正常工作

  •  0
  • Ram Singh  · 技术社区  · 7 年前

    1
    2

    SELECT * from (SELECT eventid, eventdate,eventdates FROM events WHERE events.onlineclosingdate>curdate() order by onlineclosingdate asc) a
    UNION  ALL
    SELECT * from (SELECT eventid, eventdate,eventdates FROM events WHERE events.onlineclosingdate<=curdate() order by onlineclosingdate desc) as c 
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   P.Salmon    7 年前

    例如,您可能需要识别2个日期周期块并使用条件顺序 鉴于

    drop table if exists t;
    create table t (id int auto_increment primary key, dt date);
    
    insert into t (dt) values
    ('2017-02-01'),('2017-10-01'),('2017-01-01'),
    ('2016-02-01'),('2016-10-01'),('2016-01-01');
    
    select s.id,s.dt 
    from
    (
    select 1 as srce,id,t.dt dt from t where dt > str_to_date('2016-12-31','%Y-%m-%d') 
    union all
    select 2,id,t.dt from t where dt <= str_to_date('2016-12-31','%Y-%m-%d') 
    ) s
    order by srce asc,
                case when s.srce = 1 then s.dt end asc, 
                case when s.srce = 2 then s.dt end desc;
    
    +----+------------+
    | id | dt         |
    +----+------------+
    |  3 | 2017-01-01 |
    |  1 | 2017-02-01 |
    |  2 | 2017-10-01 |
    |  5 | 2016-10-01 |
    |  4 | 2016-02-01 |
    |  6 | 2016-01-01 |
    +----+------------+
    6 rows in set (0.00 sec)
    
        2
  •  -1
  •   Ramgy Borja    7 年前

    联合两个查询并分组

    SELECT * FROM (
    SELECT a.eventid as `eventid`, a.eventdate as `eventdate`, a.eventdates as `eventdates`  FROM events a WHERE a.onlineclosingdate>curdate() order by a.onlineclosingdate asc)
    UNION  ALL
    SELECT c.eventid as `eventid`, c.eventdate as `eventdate`, c.eventdates as `eventdates` FROM events c WHERE c.onlineclosingdate<=curdate() order by c.onlineclosingdate desc)
    ) as `all` 
    

    Getting result like this