根据当前日期对即将到来的生日进行排序
我有下表的人员及其生日:
name birthday
----------------------
yannis 1979-06-29
natalia 1980-08-19
kostas 1983-10-27
christos 1979-07-22
kosmas 1978-04-28
我不知道如何根据生日与今天的距离对姓名进行排序。因此,对于 NOW() = 2011-09-08 ,排序结果应该是:
kostas 1983-10-27
kosmas 1978-04-28
yannis 1979-06-29
christos 1979-07-22
natalia 1980-08-19
我正在寻找一种快速破解方法,并不真正关心性能(宠物项目 - 表将保存少于 1000 条记录),但当然每个我们将非常感谢您的建议。
I have the following table of people and their birthdays:
name birthday
----------------------
yannis 1979-06-29
natalia 1980-08-19
kostas 1983-10-27
christos 1979-07-22
kosmas 1978-04-28
and I have no idea how to sort the names on how closer the birthday is to today. So for NOW() = 2011-09-08 the sorted result should be:
kostas 1983-10-27
kosmas 1978-04-28
yannis 1979-06-29
christos 1979-07-22
natalia 1980-08-19
I'm looking for a quick hack, don't really care for performance (pet project - table will hold less than 1000 records), but of course every suggestion will be extremely appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一种方法是:
注意:
SQLFiddle
Here is one way:
Notes:
SQLFiddle
不,由于年份有 366 天,以上可能会产生错误结果。这是正确的:
如果您的表增长到超过数千条记录,那么速度将会非常慢。如果您想要快速查询,请添加包含月份和日期的字段,并在
(bmonth,bday)
上创建索引,或者将它们添加为一个字段,即 Char (08-17 或
0817
(对于 8 月 17 日)或 Int(817
对于 8 月 17 日)以及该字段的索引。No, the above may produce error results, due to years with 366 days. This is correct:
If your table grows to more than a few thousands records, it will be real slow. If you want a fast query, add fields with the month and day and have an index on
(bmonth,bday)
or add them as one field, either Char (08-17
or0817
for 17-Aug) or Int (817
for 17-Aug) and an index on that field.似乎相当快,闰年没有问题:
Все гениальное -- просто! ;)
Seems to be rather fast, no problems with leap years:
Все гениальное -- просто! ;)
不漂亮,但是有用
Not pretty, but works
我会这样尝试(但这没有经过测试):
编辑:
将排序从
DESC
更改为ASC
,因为您希望首先获得最远的值,而不是最近的值。i would try it like this (but this isn't tested):
EDIT:
changed ordering from
DESC
toASC
because you want to get the farthest first, not the closest.