Branchwell

AI Resource Pro / website / scripts / update-category-counts-simple.sql

1-- Simple SQL to update the tool_count field in the categories table
2-- Based on log observations, we know the following columns exist:
3-- tools.category_id
4-- news.category_id
5-- blog_posts.primary_category_id
6
7-- Update category counts with the total count of instances
8UPDATE categories c
9SET tool_count = (
10 -- Count tools directly related to this category via category_id
11 SELECT COUNT(*) FROM tools
12 WHERE category_id = c.id
13) + (
14 -- Count news with this category via category_id
15 SELECT COUNT(*) FROM news
16 WHERE category_id = c.id
17) + (
18 -- Count blog posts with this category as primary_category_id
19 SELECT COUNT(*) FROM blog_posts
20 WHERE primary_category_id = c.id
21);
22
23-- Verify the results (show top 20 by count)
24SELECT
25 id,
26 name,
27 tool_count,
28 (SELECT COUNT(*) FROM tools WHERE category_id = id) AS tools_count,
29 (SELECT COUNT(*) FROM news WHERE category_id = id) AS news_count,
30 (SELECT COUNT(*) FROM blog_posts WHERE primary_category_id = id) AS blog_posts_count
31FROM
32 categories
33ORDER BY
34 tool_count DESC
35LIMIT 20;