首页 > 解决方案 > 从多个表中获取计数

问题描述

我有 3 个表,它们有一个共同的 'type_id' 列。它是来自 Table_type 的外键

Table_1 id,type_id,date... Table_2 id,type_id,date... Table_3 id,type_id,date...

Table_Type id、type_name、描述

select type_id, count(*) from Table_1 GROUP BY type_id

给出单个表的计数.

我想知道特定类型使用了多少次。

type_id,计数(来自 3 个表)
1 , 10
2 , 5
3. , 3

标签: mysqlsql

解决方案


使用union allgroup by

select type_id, count(*)
from ((select type_id from table_1) union all
      (select type_id from table_2) union all
      (select type_id from table_3)
     ) t
group by type_id

推荐阅读