AI Resource Pro / website / scripts / update-tool-count.sql
| 1 | -- SQL to properly update tool_count to reflect actual usage |
| 2 | -- Use this if you haven't renamed the column yet |
| 3 | |
| 4 | -- Begin transaction |
| 5 | BEGIN; |
| 6 | |
| 7 | -- Update the tool_count in the categories table to reflect current usage |
| 8 | UPDATE categories c |
| 9 | SET |
| 10 | tool_count = ( |
| 11 | -- Count tools with this category |
| 12 | SELECT COUNT(*) FROM tools |
| 13 | WHERE category_id = c.id |
| 14 | ) + ( |
| 15 | -- Count news with this category |
| 16 | SELECT COUNT(*) FROM news |
| 17 | WHERE category_id = c.id |
| 18 | ); |
| 19 | |
| 20 | -- Show current counts for verification |
| 21 | SELECT |
| 22 | c.id, |
| 23 | c.name, |
| 24 | c.tool_count AS current_count, |
| 25 | (SELECT COUNT(*) FROM tools WHERE category_id = c.id) AS tools_count, |
| 26 | (SELECT COUNT(*) FROM news WHERE category_id = c.id) AS news_count, |
| 27 | ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) + |
| 28 | (SELECT COUNT(*) FROM news WHERE category_id = c.id)) AS total_calculated |
| 29 | FROM |
| 30 | categories c |
| 31 | ORDER BY |
| 32 | c.tool_count DESC |
| 33 | LIMIT 20; |
| 34 | |
| 35 | -- Check for any discrepancies |
| 36 | SELECT |
| 37 | c.id, |
| 38 | c.name, |
| 39 | c.tool_count AS stored_count, |
| 40 | ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) + |
| 41 | (SELECT COUNT(*) FROM news WHERE category_id = c.id)) AS calculated_count, |
| 42 | ABS(c.tool_count - ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) + |
| 43 | (SELECT COUNT(*) FROM news WHERE category_id = c.id))) AS difference |
| 44 | FROM |
| 45 | categories c |
| 46 | WHERE |
| 47 | c.tool_count != ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) + |
| 48 | (SELECT COUNT(*) FROM news WHERE category_id = c.id)) |
| 49 | ORDER BY |
| 50 | difference DESC; |
| 51 | |
| 52 | -- Commit the transaction |
| 53 | COMMIT; |