SQL语句limit用法详解

limit就是用来拿数据前几行的,MySQL才认这个。

拿前N条很简单:select from 表 limit N。

比如limit 1 0,就是拿前1 0条。

想拿第M条开始的N条呢?写法是limit M,N。

比如limit 1 ,1 0,就是从第2 条开始拿1 0条。

下标从0开始算,别搞混了。

用limit还能提高效率,不用全表扫。

一般跟orderby一起用,先排好序再拿数据。

比如查工资最高的前5 个人:select from 员工表 order by 工资 desc limit 5
你自己看。

如何在MySQL中查询当前数据上一条和下一条的记录

嘿,你问的这事儿啊,得这么整。
你想查前一个或后一个记录,用SQL语句就行。

先说查前一个的。
这招儿是这么写的: sql select from table_a where id = ( select id from table_a where id < {$id} order by id desc limit 1 )
这玩意儿啥意思呢?就是找当前id比{$id}小的最大的那个id,然后拿这个id去table_a里查整条记录。
注意啊,如果你有别的筛选条件,得加个[and other_conditions],不然可能查错。

再说说查后一个的: sql select from table_a where id = ( select id from table_a where id > {$id} order by id asc limit 1 )
这个就好懂点了,就是找当前id比{$id}大的最小的那个id,然后去table_a里查记录。
同样,有别的条件得加上[and other_conditions]。

还有个方法,就是用max和min函数。
查前一个的: sql select from table_a where id = ( select max(id) from table_a where id < {$id} [and other_conditions] ) [and other_conditions]
这个是找比{$id}小的最大的id,然后查记录。
查后一个的: sql select from table_a where id = ( select min(id) from table_a where id > {$id} [and other_conditions] ) [and other_conditions]
这个是找比{$id}大的最小的id,然后查记录。

说实话,我一开始看这些SQL的时候,也有点懵。
但多试几次就明白啦。
关键是那个{$id},你得知道这是啥意思,一般是个变量,代表你当前查的那个id值。

希望这解释清楚了。
你要是还有啥不明白的,就再问。