const mysql = require('mysql2/promise'); async function cleanupInvalidChatData() { let connection; try { // 创建数据库连接 connection = await mysql.createConnection({ host: '1.95.162.61', port: 3306, user: 'root', password: 'schl@2025', database: 'wechat_app' }); console.log('数据库连接成功'); // 统计并删除chat_conversations表中userId为'0'或无效的记录 const [convCount] = await connection.execute( 'SELECT COUNT(*) as count FROM chat_conversations WHERE userId = ? OR userId IS NULL OR userId = ?', ['0', ''] ); console.log(`chat_conversations表中待清理记录数: ${convCount[0].count}`); if (convCount[0].count > 0) { const [convResult] = await connection.execute( 'DELETE FROM chat_conversations WHERE userId = ? OR userId IS NULL OR userId = ?', ['0', ''] ); console.log(`成功删除chat_conversations表中的 ${convResult.affectedRows} 条记录`); } // 统计并删除chat_online_status表中userId为'0'或无效的记录 const [statusCount] = await connection.execute( 'SELECT COUNT(*) as count FROM chat_online_status WHERE userId = ? OR userId IS NULL OR userId = ?', ['0', ''] ); console.log(`chat_online_status表中待清理记录数: ${statusCount[0].count}`); if (statusCount[0].count > 0) { const [statusResult] = await connection.execute( 'DELETE FROM chat_online_status WHERE userId = ? OR userId IS NULL OR userId = ?', ['0', ''] ); console.log(`成功删除chat_online_status表中的 ${statusResult.affectedRows} 条记录`); } // 统计并删除chat_messages表中sender_id或receiver_id为'0'或无效的记录 const [msgCount] = await connection.execute( 'SELECT COUNT(*) as count FROM chat_messages WHERE sender_id = ? OR sender_id IS NULL OR sender_id = ? OR receiver_id = ? OR receiver_id IS NULL OR receiver_id = ?', ['0', '', '0', ''] ); console.log(`chat_messages表中待清理记录数: ${msgCount[0].count}`); if (msgCount[0].count > 0) { const [msgResult] = await connection.execute( 'DELETE FROM chat_messages WHERE sender_id = ? OR sender_id IS NULL OR sender_id = ? OR receiver_id = ? OR receiver_id IS NULL OR receiver_id = ?', ['0', '', '0', ''] ); console.log(`成功删除chat_messages表中的 ${msgResult.affectedRows} 条记录`); } console.log('\n清理完成!数据库中的无效聊天数据已被删除。'); } catch (error) { console.error('清理过程中发生错误:', error); } finally { if (connection) { await connection.end(); console.log('数据库连接已关闭'); } } } // 执行清理操作 cleanupInvalidChatData();