我有一个 MySQL 数据库,我需要向客户端发送表中的一些数据,客户端需要获取最近的事件日期,但无法获取所有日期(使用已经到位且工作正常的分页)。 .. 所以我需要首先向客户端提供按日期最接近的事件,有些事件是 future 的,有些是过去的(客户端将通过分页获得所有这些事件),所以 order_by 本身还不够好。
我正在使用这个: events = session.query(Event).filter(user.userID == userID).order_by(desc('eventDate')
知道如何实现这一目标吗?
最佳答案
按距离当前日期的天数差异的绝对值排序?如果需要,请用当前日期替换用户选择的日期
Create table foo(
ID int,
eventDate date);
Insert into foo (ID, eventDate)
values (1,'2017-01-01'),
(2,'2017-01-02'),
(3,'2017-01-03'),
(4,'2017-01-04'),
(5,'2017-01-05'),
(6,'2017-01-06'),
(7,'2017-01-07'),
(8,'2017-01-08'),
(9,'2017-01-09');
SELECT *
FROM foo
ORDER BY abs(dateDiff(eventDate,'2017-01-05')), EventDate
返回:
ID eventDate
5 January, 05 2017 00:00:00
4 January, 04 2017 00:00:00
6 January, 06 2017 00:00:00
3 January, 03 2017 00:00:00
7 January, 07 2017 00:00:00
2 January, 02 2017 00:00:00
8 January, 08 2017 00:00:00
1 January, 01 2017 00:00:00
9 January, 09 2017 00:00:00
关于Python SqlAlchemy 按最近日期排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42285586/