在mysql

时间:2015-06-04 16:22:03

标签: mysql

id |  datetime

我如何通过ID订购,但是将最近的2个日期行添加到位置1和5?

我无法添加排序列。

这可能与sql有关,还是我需要在php中进行一些数组排序?

-------修改

id | datetime
1    2000-01-01 00:00:00
2    2000-01-01 00:00:10
3    2000-01-01 00:00:02
4    2000-01-01 00:00:09
5    2000-01-01 00:00:20
6    2000-01-01 00:00:05

我希望得到最新的2:

ids:  5,2

然后其余部分将通过id进行排序,因此它应该类似于:

ids: 5,2,1,3,4,6

2 个答案:

答案 0 :(得分:1)

在你的情况下,我建议在php方面排序。是的,可以创建将返回所需订单的mysql查询,但从性能角度看它不会非常强大

http://sqlfiddle.com/#!9/66062/1

SELECT t.*
FROM table1 t
LEFT JOIN (
  SELECT IF(@idx IS NULL,@idx:=2,@idx:=1) idx, id
  FROM table1
  ORDER BY `datetime` DESC
  LIMIT 2
  ) t1
ON t.id = t1.id
ORDER BY t1.idx DESC, t.id

答案 1 :(得分:0)

这是一种使用排名机制的方法

select
id,datetime from(
 select 
 t1.*,@rn:=@rn+1 as rn 
 from test t1,(select @rn:=0)x 
 order by datetime desc
)x
order by 
case when x.rn<=2 then 0 else 1 end,
case when x.rn<=2 then x.rn else id end
;

这是如何运作的

mysql> select * from test ;
+------+---------------------+
| id   | datetime            |
+------+---------------------+
|    1 | 2000-01-01 00:00:00 |
|    2 | 2000-01-01 00:00:10 |
|    3 | 2000-01-01 00:00:02 |
|    4 | 2000-01-01 00:00:09 |
|    5 | 2000-01-01 00:00:20 |
|    6 | 2000-01-01 00:00:05 |
+------+---------------------+

首先,我们会根据datetime

给出一些排名
 select 
 t1.*,@rn:=@rn+1 as rn 
 from test t1,(select @rn:=0)x 
 order by datetime desc

你将

+------+---------------------+------+
| id   | datetime            | rn   |
+------+---------------------+------+
|    5 | 2000-01-01 00:00:20 |    1 |
|    2 | 2000-01-01 00:00:10 |    2 |
|    4 | 2000-01-01 00:00:09 |    3 |
|    6 | 2000-01-01 00:00:05 |    4 |
|    3 | 2000-01-01 00:00:02 |    5 |
|    1 | 2000-01-01 00:00:00 |    6 |
+------+---------------------+------+

然后使用外部选择执行排序并在case-when的帮助下确定排序中的排序,如第一个查询中那样。

+------+---------------------+
| id   | datetime            |
+------+---------------------+
|    5 | 2000-01-01 00:00:20 |
|    2 | 2000-01-01 00:00:10 |
|    1 | 2000-01-01 00:00:00 |
|    3 | 2000-01-01 00:00:02 |
|    4 | 2000-01-01 00:00:09 |
|    6 | 2000-01-01 00:00:05 |
+------+---------------------+
6 rows in set (0.00 sec)