问题
I wanted to check data from documents table where there are duplicate filename or the same filename with the same employeeId and then update those filenames so that there will be no duplicates.
For example employeeId 216 has 2 or more documents with the same filenames which is DOC-15.. and DOC-15 , I wanted to rename the other file or add prefix to make it unique so that there will be no duplicates.
#Code
const documents = await sequelizeClient.query(
`SELECT id, filename, COUNT(filename) FROM documents GROUP BY filename
HAVING COUNT(filename) > 1;`,
{ type: QueryTypes.SELECT },
);
const promises = [];
// eslint-disable-next-line no-plusplus
for (let i = 0; i < documents.length; i++) {
const prefix = Date.now().toString();
const fileParts = documents[i].filename.split('.');
const finalname = `${fileParts[0]}-${prefix}.${fileParts[1]}`;
// eslint-disable-next-line no-await-in-loop
promises.push(queryInterface.sequelize.query(`UPDATE ${EmployeeDocumentsModel.tableName} SET filename='${finalname}' WHERE employeeID=${documents[i].id};`));
}
await Promise.all(promises);
#Query on getting data with duplicate filenames
SELECT id, filename, employeeId, COUNT(filename) FROM documents GROUP BY filename
HAVING COUNT(filename) > 1;
#Data
来源:https://stackoverflow.com/questions/63068502/sql-query-how-to-update-all-duplicate-filenames