使用MySQL列出属于类别表的多个表中的公共数据

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

提问人:gencyazilimci 提问时间:6/19/2021 更新时间:6/19/2021 访问量:74

问:

我有 3 张桌子。这个>类别, 博客, 课程

类别表

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

博客表格

| 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        |

课程表

| 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。拜托....

MySQL 多表

评论


答:

1赞 Tangentially Perpendicular 6/19/2021 #1

从 和 表中获取所有类别 ID,然后返回表以获取类别名称。 来计算总数。blogcourseUNION ALLJOINcategoryGROUP BYcategory_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;