如何按通用列计算实体数?

时间:2018-10-11 17:49:45

标签: mysql sql

在我的MySQL数据库中,我有2个表( ALPHA BETA )。我正在尝试发出将新列连接到ALPHA表的SQL请求。在该新列(INFO_COUNT中,我需要按INFO_ID字段存储条目数。我需要一些建议如何做到这一点。

表“ ALPHA”

       TIME_KEY      | INFO_ID | STATUS
---------------------|---------|---------
 2018-04-08 10:00:00 | 1       | Green
 2018-04-08 10:00:00 | 2       | Red
 2018-04-08 10:00:00 | 3       | Red
 2018-04-08 10:00:00 | 4       | Green
 2018-04-08 10:00:00 | 5       | Green
 2018-04-08 10:00:00 | 6       | Green
 2018-04-08 10:00:00 | 7       | Red
 2018-04-08 10:00:00 | 8       | Green
 2018-04-08 10:00:00 | 9       | Green

表'BETA'

INFO_ID | LOCATION |
--------|----------|
1       | USA      |
5       | India    |
5       | India    |
8       | China    |
9       | Canada   |
9       | Canada   |

我想要这样的结果:

       TIME_KEY      | INFO_ID | STATUS | INFO_COUNT
---------------------|---------|--------|------------
 2018-04-08 10:00:00 | 1       | Green  | 1
 2018-04-08 10:00:00 | 2       | Red    | NULL
 2018-04-08 10:00:00 | 3       | Red    | NULL
 2018-04-08 10:00:00 | 4       | Green  | NULL
 2018-04-08 10:00:00 | 5       | Green  | 2
 2018-04-08 10:00:00 | 6       | Green  | NULL
 2018-04-08 10:00:00 | 7       | Red    | NULL
 2018-04-08 10:00:00 | 8       | Green  | 1
 2018-04-08 10:00:00 | 9       | Green  | 2

1 个答案:

答案 0 :(得分:2)

这是left join和汇总。这是一种方法:

select a.*, b.info_count
from alpha a left join
     (select b.info_id, count(*) as info_count
      from b
      group by b.info_id
     ) b
     on a.info_id = b.info_id;