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

如何在MySQL中合并来自同一个表的查询,mysql,union,Mysql,Union,我有两组结果: 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 | +---------+----

我有两组结果:

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    |
+---------+---------+---------+

我该怎么做呢?

您可以使用如下自连接

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'
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'
这应该可以做到(在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

OP想要列出所有
col_1
,并在
count
列中输入NULL,没有匹配的记录。是的,这就是我要找的。谢谢^_^
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