mysql 查询开头或最后几行(Limit)
from http://hi.baidu.com/sunboy_2050/item/ccda0eceddd9a42de80f2ef0
在我们使用查询语句的时候,经常要返回前几条或者中间某几行数据

LIMIT 子句可以被用于强制 SELECT 语句返回指定的记录数。
LIMIT 接受一个或两个数字参数。参数必须是一个整数常量。
如果给定两个参数,第一个参数指定第一个返回记录行的偏移量,第二个参数指定返回记录行的最大数目。
初始记录行的偏移量是 0(而不是 1): 为了与 PostgreSQL 兼容,MySQL 也支持句法: LIMIT # OFFSET #。









示例:
select top, id, dtime from gametop800 where top=1 order by dtime limit 0, 10;
查询后n行记录
select * from table order by id desc limit n;//倒序排序(desc)
查询一条记录($id)的下一条记录
select * from table where id>$id order by id asc limit 1
查询一条记录($id)的上一条记录
select * from table where id<$id order by id desc limit 1
示例:
select top, id, dtime from gametop800 where top=1 order by dtimedesclimit 0, 10;
上面查询最后n行记录,虽然可以通过desc倒排实现,但最终的结果集也是倒排的
要使desc倒排后,结果集依然能够哦asc升序排列,我们可以借助数据库子表查询实现
即在子表的查询条件中,重新把desc结果进行asc排列
示例:
select * from (select top, id, dtime from gametop800 where top=1 order by dtimedesclimit 0, 10) as tbl order by dtime asc;
最后,附上一个案例
select * from wap_content where week(created_at) = week(now)
如果你要严格要求是某一年的,那可以这样
查询一天:
select * from table where to_days(column_time) = to_days(now());
select * from table where date(column_time) = curdate();
查询一周:
select * from table where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(column_time);
查询一个月:
select * from table where DATE_SUB(CURDATE(), INTERVAL INTERVAL 1 MONTH) <= date(column_time);