mysql逆记录提取顺序

时间:2014-09-11 21:10:01

标签: mysql sql

我正在尝试以相反的顺序获取插入mysql表中的最后5条记录:

但是使用以下查询我无法做到这一点,我已经读过subquery可以做到这一点,但确切地说在哪里申请,我很困惑:

这是我的表

select "1" as s,`to` as f, message as m,sent  
from table1 where chat.`to` = "user1" 
union 
select "1" as s,`to` as f, message as m,sent  
from table1 where chat.`from` = "user1" 
ORDER BY sent DESC
limit 5

目前是结果

1   v         bbye              10  2014-09-12 02:17:06
1   Gv        not interested    9   2014-09-12 02:17:04
1   Get       football          8   2014-09-12 02:16:55
1   Get       let's play        7   2014-09-12 02:16:50
1   Gv        ok great work     6   2014-09-12 02:16:43

这是我想要做的以下方式

1   Gv        ok great work     6   2014-09-12 02:16:43
1   Get       let's play        7   2014-09-12 02:16:50
1   Get       football          8   2014-09-12 02:16:55
1   Gv        not interested    9   2014-09-12 02:17:04
1   v         bbye              10  2014-09-12 02:17:06

1 个答案:

答案 0 :(得分:0)

子查询的格式如下:

select * from(
  select *
  from
   (select "1" as s,`to` as f, message as m,sent  
    from table1 where chat.`to` = "user1" 
    union 
    select "1" as s,`to` as f, message as m,sent  
    from table1 where chat.`from` = "user1" ) u
  ORDER BY sent DESC
  limit 5) o order by sent

正如@GGio指出的那样,重构查询以使用OR会更有效:

select * from (
  SELECT "1" as s, `to` as f, message as m, sent
  FROM table1
  WHERE chat.`to` = "user1" OR chat.`from` = "user1"
  ORDER BY sent DESC
  LIMIT 5) o
order by sent