簡體   English   中英

從多個表中獲取計數

[英]get count from multiple tables

我有 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, count(from 3 tables)
1      , 10
2      , 5
3 .    , 3

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

從每個表中獲取計數,將這些查詢與UNION結合,然后將計數相加。

SELECT type_id, SUM(count)
FROM (
    SELECT type_id, COUNT(*) AS count
    FROM table_1
    UNION ALL
    SELECT type_id, COUNT(*) AS count
    FROM table_2
    UNION ALL
    SELECT type_id, COUNT(*) AS count
    FROM table_3
) AS x
GROUP BY type_id

如果type_id列上有索引,則此查詢應該能夠利用它們。 UNION處理較小的表,因為它在分組后合並。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM