分页 LIMIT
57.15 分页 LIMIT
LIMIT n 只取前 n 条;LIMIT offset, count 跳过 offset 条后取 count 条。
MySQL 8+ 推荐 LIMIT count OFFSET offset;配合 ORDER BY 做排行榜、分页。
前三名与分页
import pymysql
conn = pymysql.connect(host='127.0.0.1', user='root', password='root', database='py_demo', charset='utf8mb4')
try:
with conn.cursor() as cur:
cur.execute('SELECT name, score FROM students ORDER BY score DESC LIMIT 3')
print('前三名:', cur.fetchall())
page, size = 2, 2 # 第2页,每页2条
offset = (page - 1) * size
cur.execute(
'SELECT name, score FROM students ORDER BY id LIMIT %s OFFSET %s',
(size, offset)
)
print('第2页:', cur.fetchall())
finally:
conn.close()