DB

(게시판에서 동작되는 SQL Query문) 검색과 페이징이 포함된 게시물 리스트와 게시물수 조회

「김동윤」 2021. 9. 24. 19:36

 



1. 전체 게시물 리스트 조회(검색과 페이징 포함)

-> 사용자가 제목 또는 작성자 또는 내용 또는 제목+내용인 조건으로 검색하게 될텐데 조건이 달라질때마다 테이블조회 조건인 where절도 달라져야 하므로 동적SQL을 써주었습니다. like뒤에 concat('%',#{keyword},'%')을 사용한 이유는 like "%#{keyword}#%"로 써주게 되면 #{keyword}를 문자열로 인식하기 때문에 문자열을 연결시켜주는 명령어인 concat을 사용하여 주었습니다. 그리고 마지막에 limit절을 써준 이유는 예를 들어 게시물을 5개로 나눠서 순차적으로 조회한다고 가정하면 SQL Query문에서는 limit절을 limit 0,5 -> limit 5,5 -> limit 10,5 이런식으로 작성해주어야 하기때문에 limit절을 사용하여 작성하였습니다.

startPage의 공식: (page-1) * countPerPage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<select id="getAllArticles" resultMap="BoardMap">
        select *
        from board
        <if test="condition=='title'">
        where title
        like concat('%',#{keyword},'%')
        </if>
        <if test="condition=='writer'">
        where writer
        like concat('%',#{keyword},'%')
        </if>
        <if test="condition=='content'">
        where title
        like concat('%',#{keyword},'%')
        </if>
        <if test="condition=='titleContent'">
        where title
        like concat('%',#{keyword},'%')
        or content
        like concat('%',#{keyword},'%')
        </if>
        limit #{startPage},#{countPerPage}
</select>
    
cs

 

 





2. 전체 게시물수 조회(검색 페이징 포함)
-> select count(*) from board 쿼리문을 통해 전체 게시물 수를 조회합니다. 하지만 검색과 페이징이 포함된 게시물을 조회하는 것이기 때문에 위의 전체 게시물 리스트 조회(검색과 페이징 포함)와 같이 동적SQL과 limit절을 추가한뒤 조회하여 주어야 합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<select id="countArticles" resultType="int">
        select count(*)
        from board
        <if test="condition=='title'">
        where title
        like concat('%',#{keyword},'%')
        </if>
        <if test="condition=='writer'">
        where writer
        like concat('%',#{keyword},'%')
        </if>
        <if test="condition=='content'">
        where title
        like concat('%',#{keyword},'%')
        </if>
        <if test="condition=='titleContent'">
        where title
        like concat('%',#{keyword},'%')
        or content
        like concat('%',#{keyword},'%')
        </if>
</select>
cs