列出多个 table 中属于类别 table 和 MySQL 的公共数据

Listing common data in multiple tables belonging to a category table with MySQL

我有 3 个 table。此-> 类别、博客、课程

类别table

| category_id | category_name |
|      1      |  php          |
|      2      |  python       |
|      3      |  javascript   |

博客table

| blog_id | blog_title | blog_category_id |
|    1    | trial 1    |         1        |
|    2    | trial 2    |         2        |
|    3    | trial 3    |         1        |
|    4    | trial 4    |         2        |
|    5    | trial 5    |         3        |
|    6    | trial 6    |         1        |
|    7    | trial 7    |         3        |

课程table

| course_id | course_title | course_category_id |
|    1      | trial 1      |         1          |
|    2      | trial 2      |         3          |
|    3      | trial 3      |         2          |
|    4      | trial 4      |         1          |
|    5      | trial 5      |         1          |
|    6      | trial 6      |         1          |
|    7      | trial 7      |         3          |

输出:

| category_name | TotalCount |
|    php        |     7      |
|    python     |     3      |
|    javascript |     4      |

如何列出这样的输出 MySQL。拜托....

blogcourse table 中获取所有类别 ID,然后使用 UNION ALL 然后 JOIN 返回 category table 获取类别名称。 GROUP BY category_id 计算总数。

结果如下所示:

SELECT COUNT(category.category_id), category_name FROM category 
    JOIN (
      SELECT blog_category_id AS category_id FROM blog 
      UNION ALL 
      SELECT course_category_id AS category_id FROM course
    ) a ON 
    (category.category_id = a.category_id)
 GROUP BY category.category_id;