-- SQL to properly update tool_count to reflect actual usage -- Use this if you haven't renamed the column yet -- Begin transaction BEGIN; -- Update the tool_count in the categories table to reflect current usage UPDATE categories c SET tool_count = ( -- Count tools with this category SELECT COUNT(*) FROM tools WHERE category_id = c.id ) + ( -- Count news with this category SELECT COUNT(*) FROM news WHERE category_id = c.id ); -- Show current counts for verification SELECT c.id, c.name, c.tool_count AS current_count, (SELECT COUNT(*) FROM tools WHERE category_id = c.id) AS tools_count, (SELECT COUNT(*) FROM news WHERE category_id = c.id) AS news_count, ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) + (SELECT COUNT(*) FROM news WHERE category_id = c.id)) AS total_calculated FROM categories c ORDER BY c.tool_count DESC LIMIT 20; -- Check for any discrepancies SELECT c.id, c.name, c.tool_count AS stored_count, ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) + (SELECT COUNT(*) FROM news WHERE category_id = c.id)) AS calculated_count, ABS(c.tool_count - ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) + (SELECT COUNT(*) FROM news WHERE category_id = c.id))) AS difference FROM categories c WHERE c.tool_count != ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) + (SELECT COUNT(*) FROM news WHERE category_id = c.id)) ORDER BY difference DESC; -- Commit the transaction COMMIT;