-- SQL to properly update instance_count values -- This script assumes the column has been renamed from tool_count to instance_count -- Begin transaction BEGIN; -- Update the instance_count in the categories table to reflect correct usage UPDATE categories c SET instance_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.instance_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.instance_count DESC LIMIT 20; -- Check for any discrepancies SELECT c.id, c.name, c.instance_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.instance_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.instance_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;