본문 바로가기
WEB/Nodejs-mysql

[Nodejs-mysql] Join된 테이블에서 값 가져오기

by Ellen571 2020. 8. 6.

[생활코딩] MySQL join을 이용해서 상세보기 구현

 

db.query('SELECT*FROM topic', function(error, topics){
          if(error){ throw error;}
          
          db.query('SELECT*FROM topic LEFT JOIN author ON topic.author_id = author.id WHERE topic.id=?', [queryData.id], function(error2, topic){
          // JOIN LEFT로 topic과 author 데이터 가져오기
          // ON으로 두 테이블 매칭시키기
          // WHERE에서 어떤 테이블의 id값 가져올지 명시하기
          
            if(error2){throw error2;}

            var title = topic[0].title;
            var description = topic[0].description;
            var list = template.list(topics);
            var html = template.HTML(title, list,            
                  `<h2>${title}</h2>${description}<p>By ${topic[0].name}</p>`,
                  ` <a href="/create">create</a>
                    <a href="/update?id=${queryData.id}">update</a>
                    <form action="delete_process" method="post">
                      <input type="hidden" name="id" value="${queryData.id}">
                      <input type="submit" value="delete">
                    </form>`
            );
            // topic[0].name으로 author의 name값 출력하기
            
            response.writeHead(200);
            response.end(html);
          });
});
반응형