代码之家  ›  专栏  ›  技术社区  ›  khairul

如何在MySQL中联合来自同一表的查询

  •  5
  • khairul  · 技术社区  · 17 年前

    我有两组结果:

    SELECT name, count(appearance) as countA from table where results = '1'
    SELECT name, count(appearance) as countB from table where results = '2'
    

    我想把它们并排放在一起,就像这样:

    +---------+---------+---------+
    | col_1   | countA  | countB  |
    +---------+---------+---------+
    | John    |    3    |    1    |
    | Mary    |    1    |    2    |
    | Gary    |    2    |   NULL  |
    | Sean    |    4    |   NULL  |
    | Mike    |  NULL   |    6    |
    +---------+---------+---------+
    

    我该怎么做?

    4 回复  |  直到 17 年前
        1
  •  5
  •   PaulJ    17 年前

    这应该可以在不需要自连接的情况下完成(在Oracle中)

    SELECT name
         , sum( case results when '1' then 1 else 0 end ) as countA 
         , sum( case results when '2' then 1 else 0 end ) as countB
      from table 
     where results IN ( '1', '2' )
     group by
           name
    
        2
  •  1
  •   Rahul    17 年前

    您可以按如下方式使用自连接

    select a.col_1, a.countA, b.countB from table a, table b
    where a.col_1 = b.col_1 and a.results='1' and b.results='2'
    
        3
  •  -1
  •   Rigobert Song    17 年前
    SELECT name, count(appearance) as countA, null AS countB from table where results = '1'
    UNION ALL
    SELECT name, null AS countA, count(appearance) as countB from table where results = '2'
    
        4
  •  -1
  •   Zed    17 年前
    SELECT `table`.name, countA, countB
    FROM tab
    LEFT OUTER JOIN
      (SELECT name, count(appearance) as countA from `table` where result = '1' group by name) as tmp1
    ON `table`.name = tmp1.name
    LEFT OUTER JOIN
      (SELECT name, count(appearance) as countB from `table` where result = '2' group by name) as tmp2
    ON `table`.name = tmp2.name;