[홈페이지 제작] 홈페이지 댓글 만들기 2 - 쿼리문 연습

Feb 20, 2024
[홈페이지 제작] 홈페이지 댓글 만들기 2 - 쿼리문 연습
 
더미데이터 추가
insert into reply_tb(comment,board_id,user_id,created_at) values ('댓글1',1,1,now()); insert into reply_tb(comment,board_id,user_id,created_at) values ('댓글2',4,1,now()); insert into reply_tb(comment,board_id,user_id,created_at) values ('댓글3',4,1,now()); insert into reply_tb(comment,board_id,user_id,created_at) values ('댓글4',4,2,now());
notion image
 
더미데이터를 추가한다.
 
notion image
 
댓글 테이블과 게시글 테이블을 join 한다.
게시글 테이블 board_tb의 id 와 reply_tb 의 board_id를 통해 조인한다.
 

쿼리연습

 
 
select * from board_tb bt inner join reply_tb rt on bt.id = rt.board_id ;
notion image
 
inner join을 사용하면 댓글이 있는 게시글만 조회가 된다.
 
댓글이 없어도 게시글은 조회가 되어야 하기 때문에 outer join 을 사용해야 한다.
 
 

아우터 조인(게시글 목록보기 - 댓글 카운트 보이기)

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.title,bt.content,bt.user_id,bt.created_at;
notion image
 
게시글의 댓글 수를 조회한다.

아우터조인(게시글 목록보기-댓글도 함께 보이기)

select bt.id, bt.title, bt.content, bt.user_id, bt.created_at, ifnull(rt.id, 0) rid, rt.board_id, ifnull(rt.comment,'') from board_tb bt left outer join reply_tb rt on bt.id = rt.board_id;
 
notion image
이 상태로 리퀘스트 객체에 담아서 view 에 넘기면, 게시글4 가 3번 표시된다.
 
💡
화면에 출력할 때 반복문 6번 돌게 되면 제목4가 3번 표시됨. 따라서 DB에서 받는 DTO, 화면에 출력하는 DTO 를 따로 만들어야 한다.
 
notion image
 
테이블을 각각 DetailDTO 와 ReplyDTO 로 담는다.
 
Share article
RSSPowered by inblog