blog 댓글 쓰기

[Spring] 댓글 쓰기 구현
Feb 21, 2024
blog 댓글 쓰기
조인을 하는 이유 - 2개의 데이터를 다 보여주기 위해서

게시글 목록보기

notion image
notion image
notion image

게시글 목록에서 댓글 함께 보이기(그냥 해보는거임)

이너 조인

select * from board_tb bt inner join reply_tb rt on bt.id = rt.board_id;
notion image
제목 1,2,3,4중 제목1, 제목4만 결과로 나옴 댓글이 없어도 board_title은 나와야함.

아우터 조인

select bt.*,rt.* from board_tb bt left outer join reply_tb rt on bt.id = rt.board_id;
notion image
이상태로 화면에 뿌리면 게시글이 6개가 출력된다. 게시물은 4개이므로 4번만 출력되어야 함.
DB에서 불러오는 DTO, 화면에 전달하는 DTO 총 2개를 만들어야함.
notion image

아우터 조인 그룹으로 묶기

select bt.*,rt.id from board_tb bt left outer join reply_tb rt on bt.id = rt.board_id ;
notion image
select bt.*,count(rt.id) from board_tb bt left outer join reply_tb rt on bt.id = rt.board_id group by bt.id, bt.user_id, bt.created_at, bt.content, bt.title;
notion image
위의 결과를 화면에 뿌리면 됨

게시글 상세보기에서 댓글 보이기

두가지 방법 중 하나의 방법을 사용해야함.

아우터 조인+ 이너 조인 → 성능이 더 좋다.

select bt.id, bt.title, bt.content, bt.user_id, but.username, bt.created_at, rt.id r_id, rt.user_id r_user_id, rut.username, rt.comment from board_tb bt left outer join reply_tb rt on bt.id = rt.board_id inner join user_tb but on bt.user_id = but.id left outer join user_tb rut on rt.user_id = rut.id where bt.id = 4;
notion image
notion image
null은 아무 값도 표시하지 않음 → 그래야 댓글이 없는 곳은 null값이 안뜬다.
위의 결과를 화면에 뿌리면 된다.

쿼리 두번 작성하기 → 가독성이 더 좋다.

select * from board_tb bt inner join user_tb ut on bt.user_id = ut.id where bt.id = 4;
notion image
select * from reply_tb rt inner join user_tb ut on rt.user_id = ut.id where rt.board_id = 4;
notion image
 
Share article
RSSPowered by inblog