我正在尝试以相反的顺序获取插入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
答案 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