4

2 つのテーブルがあります。Table1 は次のようになります。

id   type    
1    bike     
2    car      
3    cycle
4    bike

Table2 は次のようになります。

id   type    
1    bike     
2    car 

最終的な出力を次のようにします。

type   count_table1   count_table2
bike        2            1
car         1            1 
cycle       1            0

SQLでこれを行う最も効率的な方法は何ですか?

4

7 に答える 7

3

シンプルなソリューションで、複雑なテーブル結合と関数は必要ありません:

SELECT type, MAX(count_table1) as count_table1, MAX(count_table2) as count_table2 FROM (
(
    SELECT type, COUNT(*) AS count_table1, 0 AS count_table2
    FROM Table1
    GROUP BY type
) UNION (
    SELECT type, 0 AS count_table1, COUNT(*) AS count_table2
    FROM Table2
    GROUP BY type)
) AS tmp
GROUP BY type

SQL フィドル

于 2013-08-28T07:23:22.873 に答える
2

これを試すことができます:

SELECT t1.TYPE, 
       ifnull(t1.COUNT1,0) CountTable1, 
       ifnull(t2.COUNT2,0) CountTable2 
FROM   (SELECT TYPE, 
               COUNT(*) count1 
        FROM   TABLE1 
        GROUP  BY TYPE)T1 
       LEFT JOIN (SELECT TYPE, 
                         COUNT(*) count2 
                  FROM   TABLE2 
                  GROUP  BY TYPE)T2 
              ON t1.TYPE = t2.TYPE 
UNION 
SELECT t1.TYPE, 
       t1.COUNT1, 
       t2.COUNT2 
FROM   (SELECT TYPE, 
               COUNT(*) count1 
        FROM   TABLE1 
        GROUP  BY TYPE)T1 
       RIGHT JOIN (SELECT TYPE, 
                          COUNT(*) count2 
                   FROM   TABLE2 
                   GROUP  BY TYPE)T2 
               ON t1.TYPE = t2.TYPE 

SQL Fiddleに関する私の作業例を参照してください。

于 2013-08-28T07:17:06.147 に答える
2
SELECT a.TYPE, 
       COUNT(a.ID), 
       COUNT(b.ID) 
FROM   TABLE1 AS a 
       LEFT OUTER JOIN TABLE2 AS b 
                    ON a.TYPE = b.TYPE 
GROUP  BY a.TYPE 
UNION 
SELECT b.TYPE, 
       COUNT(a.ID), 
       COUNT(b.ID) 
FROM   TABLE1 AS a 
       RIGHT OUTER JOIN TABLE2 AS b 
                     ON a.TYPE = b.TYPE 
GROUP  BY b.TYPE 
于 2013-08-28T07:17:47.757 に答える
1
select type, count(*) from table1 group by type

select type, count(*) from table2 group by type

各アイテムのカウントを取得する

于 2013-08-28T07:16:43.783 に答える
0
select
    T.type
    ,IFNULL(COUNT(T1.type),0) as 'count_table1'
    ,IFNULL(COUNT(T2.type),0) as 'count_table2'
from
    Table1 as T1
    left join Table2 as T2 on T2.id = T1.id
group by
    T.type

union

select
    T.type
    ,IFNULL(COUNT(T1.type),0) as 'count_table1'
    ,IFNULL(COUNT(T2.type),0) as 'count_table2'
from
    Table2 as T
    left join Table1 as T1 on T1.id = T2.id
group by
    T.type
于 2013-08-28T07:17:15.460 に答える