Branchwell

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
5BEGIN;
6
7-- Update the tool_count in the categories table to reflect current usage
8UPDATE categories c
9SET
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
21SELECT
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
29FROM
30 categories c
31ORDER BY
32 c.tool_count DESC
33LIMIT 20;
34
35-- Check for any discrepancies
36SELECT
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
44FROM
45 categories c
46WHERE
47 c.tool_count != ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) +
48 (SELECT COUNT(*) FROM news WHERE category_id = c.id))
49ORDER BY
50 difference DESC;
51
52-- Commit the transaction
53COMMIT;