MySQL에서 받아온 데이터 중복 제거하기
최근에 유저 페이지 개발을 진행하면서 기술명으로 검색을 진행하였을 때 결과 데이터에서 발생하는 유저 데이터를 다시 반환하여 검색 결과를 표시해주려는 작업을 진행하면서 프로젝트들의 기술명으로 검색이 걸린 결과물을 반환하면 결국 유저 데이터들의 중복이 발생하기에 중복을 제거해야 한다는 문제점이 발생하였습니다.
지금까지 MySQL의 SQL문을 사용해본건 기본적인 SQL문과 그때그때 필요한 기능들을 검색해보면서 사용하고 있는데 이 부분으로 질문을 하면서 'distinct'라는 SQL문을 알 수 있게 되었습니다.
제가 기존에 사용한 코드는 아래와 같습니다.
router.get(`/find-users/:queryString`, function(req, res, next) {
let queryString = req.params.queryString;
db.query(
`SELECT userId from project WHERE keyword like "%${queryString}%"`,
function(error, data) {
console.log(data);
}
);
res.json(data);
});
결과물은 아래와 같이 반환되는데 문제의 중복되는 데이터들이 보입니다.
[ RowDataPacket { userId: 'arpitjindal97' },
RowDataPacket { userId: 'cs01' },
RowDataPacket { userId: 'samuelcolvin' },
RowDataPacket { userId: 'Jyrno42' },
RowDataPacket { userId: 'LemonyDesign' },
RowDataPacket { userId: 'thruthesky' },
RowDataPacket { userId: 'thruthesky' },
RowDataPacket { userId: 'thruthesky' },
RowDataPacket { userId: 'thruthesky' },
RowDataPacket { userId: 'apollographql' },
RowDataPacket { userId: 'samuelcolvin' },
RowDataPacket { userId: 'Jyrno42' },
RowDataPacket { userId: 'Jyrno42' },
RowDataPacket { userId: 'thruthesky' }
}
위의 코드를 아래처럼 distinct를 사용하여 처음부터 중복 값을 제거한 상태로 데이터를 반환하도록 하였습니다. 물론 데이터를 그냥 받아온 후에 JS로 중복값을 제거하는 방법도 있겠지만 처음부터 DB 서버에서 중복값을 제거한 데이터를 가져올 수 있다면 이 방법이 더 좋은 것 같습니다.
router.get(`/find-users/:queryString`, function(req, res, next) {
let queryString = req.params.queryString;
db.query(
`SELECT distinct userId from project WHERE keyword like "%${queryString}%"`,
function(error, data) {
console.log(data);
}
);
res.json(data);
});
해당 Stackoverflow 게시글 링크는 아래와 같습니다
How to remove duplicate data in JavaScript RowDataPacket Array
I got a data from my MySQL Server with Nodejs and I want to remove duplicate data in this array, but the structure of the array looks weird and I tried various method to solve this problem but, it's
stackoverflow.com