试图结合计数和左连接

时间:2014-06-09 13:55:12

标签: sql sqlite count subquery left-join

我有三个表,每个表只有一个我关心的列,用于此查询:

Table A 
**Color**
Red
Blue 
Green
Purple

Table B
**Color**
Pink
Black
Blue
Green
Blue
Green

Table C
**Color**
Orange 
Purple
Purple
Red

我想用A和B和C进行左连接并获得每种颜色的计数。我想要一个看起来像这样的结果:

Color CountA CountB CountC
Red    1      0      1
Blue   1      2      0
Green  1      2      0
Purple 1      0      2

当我使用内连接进行计数时,它会增加一些奇怪的数字。我认为这是我的GROUP BY子句。

2 个答案:

答案 0 :(得分:1)

SQL Fiddle

SELECT Color,
(
  SELECT Count(*) 
  FROM TableA a
  WHERE a.Color = m.color
) AS CountA,
(
  SELECT Count(*) 
  FROM TableB b
  WHERE b.Color = m.color
) AS CountB,
(
  SELECT Count(*) 
  FROM TableC c
  WHERE c.Color = m.color
) AS CountC
FROM TableA m
GROUP BY m.Color;

答案 1 :(得分:0)

我想说两点。第一种可能是编写查询的更有效方式:

SELECT Color, Count(*) as CountA,
       (SELECT Count(*) 
        FROM TableB b
        WHERE b.Color = a.color
       ) AS CountB,
       (SELECT Count(*) 
        FROM TableC c
        WHERE c.Color = a.color
       ) AS CountC
FROM TableA a
GROUP BY a.Color;

请注意,如果A没有重复项,则更好的方法是:

SELECT Color, 1 as CountA
       (SELECT Count(*) 
        FROM TableB b
        WHERE b.Color = a.color
       ) AS CountB,
       (SELECT Count(*) 
        FROM TableC c
        WHERE c.Color = a.color
       ) AS CountC
FROM TableA a;

即,删除该组。

第二点是tableB(颜色)和tableC(颜色)的索引将有助于提高性能,