使用UNION ALL时如何让数据return为0?

How to make the data return 0 when using UNION ALL?

当使用UNION ALL时,数据不会return0。例如,如果table分数中高的频率为零,则不会return什么。这就是为什么我想在我的代码中应用外连接

表 1

  id    |   myid     |    score       |
---------------------------------------
1       |    20      |    high        |
2       |    20      |    low         |
3       |    21      |    average        |
4       |    21      |    high        |
5       |    21      |    low         |

表2

 id2    |   myid     |   score      |
-------------------------------------
1       |    21      |   high       |
2       |    21      |   low        |
3       |    20      |   low        |
4       |    20      |   low        |
5       |    20      |   low        |

我得到的输出为 myid=20

myid     |  score       | f  |
-------------------------------
 20      |   low        | 4   |
 20      |   high       | 1   |  

期望输出

 myid    |  score       | f  |
-------------------------------
 20      |   low        | 4   |
 20      |   high       | 1   |  
 20      |   average    | 0   | 

我的代码:

select myid, score, count(*) as f
from
(
  select myid, score from table1 where myid=12
  union all
  select myid, score from table2 where myid=12
) unioned
group by myid, score

您应该合并两个表,然后对其进行聚合:

SELECT
    myid,
    score,
    COUNT(*) AS f
FROM
(
    SELECT myid, score FROM table1
    UNION ALL
    SELECT myid, score FROM table2
) t
GROUP BY
    myid,
    score;

您可以使用 UNION 两个表,然后 GROUP BY myid。例如:

select
  myid, score, count(*) as f
from (
  select myid, score from table1
  union all
  select myid, score from table2
) x
group by myid, score

编辑:

如果您希望在没有行的情况下始终将 highlow 值显示为零,您可以使用 LEFT JOIN 来实现:

select myid, score, sum(c) as f
from (
  select 'low' as score union select 'high'
) s
left join (
  select myid, score, 1 as c from table1
  union all
  select myid, score, 1 from table2
) x on x.score = s.score
group by myid, score

请注意,我没有测试最后一个查询。

UNION ALL 查询不够,因为它可能不包含 score 的所有可能值:'high''low''average'
使用 returns 所有这些可能值的查询并左加入 UNION ALL 查询:

select s.score, count(t.score) f
from (select 'high' score union all select 'low' union all select 'average') s
left join (
  select * from Table1 where myid = 20
  union all
  select * from Table2 where myid = 20
) t on t.score = s.score
group by s.score

参见demo
结果:

> score   |  f
> :------ | -:
> average |  0
> high    |  1
> low     |  4