본문 바로가기
프로그래밍/기타

[SQL] 게시판 상세화면에서 이전글 다음글 구현 쿼리

by 공대부부 남편 2025. 1. 14.
728x90
반응형

최근에 게시물 관련 웹개발을 진행하면서 게시글의 상세화면에서 하단부에 이전글, 다음글을 노출시켜 개발을 진행하게 되어 진행한 방법을 공유합니다.

 

우선 선택한 게시글 기준으로 이전글, 이후글을 상세화면에서 데이터로 갖게 되면 되기에 lead, lag 함수를 이용해서 조회했습니다.

 

데이터는 다음과 같이 목업데이터로 type이 먹방, 여행 두가지 타입중에 각각 타입별 이전글, 이후글을 노출해야합니다.

 

 

seq 3 인 먹방 타이틀2 제목의 

이전글  = seq 1 / 먹방 타이틀 1 

이후글 = seq 4 / 먹방타이틀 3

 

with DUAL as (
	select 1 as seq, '먹방 타이틀1' as title, 'eating' as type
	union ALL
	select 2 as seq, '여행 타이틀1' as title, 'travel' as type
	union ALL
	select 3 as seq, '먹방 타이틀2' as title, 'eating' as type
	union ALL
	select 4 as seq, '먹방 타이틀3' as title, 'eating' as type
	union ALL
	select 5 as seq, '여행 타이틀2' as title, 'travel' as type
	union ALL
	select 6 as seq, '여행 타이틀3' as title, 'travel' as type
)
select seq
     , lead(seq) over (partition by type order by seq) as next
     , lag(seq) over (partition by type order by seq) as prev
  from DUAL
 where 1 = 1

 

seq : 현재글 

next : 현재글 기준 같은 type의 다음글 

prev : 현재글 기준 같은 type의 이전글 

 

 

728x90
반응형