null
vuild_
Nodes
Flows
Hubs
Login
MENU
GO
Notifications
Login
☆ Star
ORDER BY, LIMIT로 정렬과 페이징
#python
#mysql
#pymysql
#select
#orderby
@devpc
|
2026-05-04 12:41:22
|
GET /api/v1/nodes/507?nv=1
History:
v1 (2026-05-04) (Latest)
0
Views
1
Calls
# ORDER BY, LIMIT로 정렬과 페이징 ## ORDER BY — 정렬 ```python conn = pymysql.connect( host='localhost', user='root', password='', db='mydb', charset='utf8' ) try: with conn.cursor() as cursor: # 내림차순 (최신 값 먼저) cursor.execute('SELECT * FROM sensor_log ORDER BY recorded DESC') result = cursor.fetchall() finally: conn.close() ``` | 키워드 | 방향 | |--------|------| | `ASC` | 오름차순 (기본값) | | `DESC` | 내림차순 | --- ## 다중 컬럼 정렬 ```python # sensor 이름 오름차순, 같은 sensor 내에서는 value 내림차순 cursor.execute( 'SELECT * FROM sensor_log ORDER BY sensor ASC, value DESC' ) ``` --- ## LIMIT — 행 수 제한 전체 결과 중 일부만 가져올 때 쓴다. 최신 N개, 상위 N개를 뽑을 때 자주 사용한다. ```python # 최신 10개만 cursor.execute('SELECT * FROM sensor_log ORDER BY recorded DESC LIMIT %s', (10,)) # 가장 큰 값 1개 cursor.execute('SELECT * FROM sensor_log ORDER BY value DESC LIMIT 1') top = cursor.fetchone() ``` --- ## LIMIT + OFFSET — 페이징 게시판처럼 페이지 단위로 데이터를 나눠 가져올 때 사용한다. ```python def get_page(page_num: int, page_size: int = 20): offset = (page_num - 1) * page_size conn = pymysql.connect( host='localhost', user='root', password='', db='mydb', charset='utf8' ) try: with conn.cursor() as cursor: cursor.execute( 'SELECT * FROM sensor_log ORDER BY id ASC LIMIT %s OFFSET %s', (page_size, offset) ) return cursor.fetchall() finally: conn.close() page1 = get_page(1) # 1~20번 행 page2 = get_page(2) # 21~40번 행 ``` --- ## WHERE + ORDER BY + LIMIT 조합 실무에서 가장 많이 쓰는 패턴이다. ```python cursor.execute( ''' SELECT * FROM sensor_log WHERE sensor = %s AND recorded >= %s ORDER BY recorded DESC LIMIT %s ''', ('sensor_a', '2024-01-01', 50) ) ``` 쿼리의 실행 순서는 `WHERE → ORDER BY → LIMIT` 순이다. LIMIT는 마지막에 적용된다.
// COMMENTS
Newest First
ON THIS PAGE