繁体   English   中英

MySQL计算数据透视表上至少有一条记录的所有记录

[英]MySQL count all records that have at least one record on a pivot table

我正在尝试查看表的记录是否在用于多对多关系的数据透视表上至少有一条记录。

表话务员是:

| ID |  NAME  |
|----|--------|
| 1  | Name A |
| 2  | Name B |
| 3  | Name C |

并且Attendant_Event数据透视表具有以下结构

| ID |  attendant_id  |  event_id  |  uuid  |
|----|----------------|------------|--------|
| 1  |       1        |      1     |   xxx  |
| 2  |       1        |      2     |   yyy  |
| 3  |       3        |      1     |   zzz  |
| 4  |       3        |      2     |   www  |
| 5  |       1        |      3     |   xyx  |
| 6  |       3        |      3     |   rer  |

我的查询正在尝试对数据透视表上具有至少一条记录的服务员进行计数,但将所有记录都视为一个。 例如,预期结果将是一个如下表:

| STATUS |  COUNT |
|--------|--------|
|   YES  |    2   | 
|   NO   |    1   |

预期会出现此结果,因为:

  1. 只有ID为1和3的话务员才在Attendant_Event表上有一条记录。 这告诉我们,数据透视表上带有行的话务员数量为2。
  2. ID为2的话务员没有记录,因此数据透视表上没有记录的话务员数量为1。

现在,我的查询如下:

SELECT IF(uuid <=> NULL, 'NO', 'YES') as status, count(*) as count FROM attendants att LEFT JOIN attendant_event ae ON ae.attendant_id = att.id GROUP BY status

但这向我展示了这样的结果。

| STATUS |  COUNT |
|--------|--------|
|   YES  |    6   | 
|   NO   |    1   |

这意味着,对每一行进行计数。 如果我们采用前面的示例,则ID为1和3的两个话务员在数据透视表上都有3条记录。 所以它给出了6个而不是我要的两个。

我做错了什么?

您可能需要先选择带有各自的是/否的话务员ID,然后对它们进行计数,例如:

SELECT status, count(distinct attendant_id) as count FROM (
   SELECT IF(ae.uuid IS NULL, 'NO', 'YES') as status, ae.attendant_id
   FROM attendants att LEFT JOIN attendant_event ae ON ae.attendant_id = att.id
   GROUP BY ae.attendant_id) x
GROUP BY status

当您进行左联接时,您将创建相交,该相交大于服务员表。 您的联接由具有重复的attendant_id和不同事件uuid的行组成。

您可以通过执行SELECT IF(uuid <=> NULL, 'NO', 'YES') as status, att.id, ae.uuid FROM attendants att LEFT JOIN attendant_event ae ON ae.attendant_id = att.id 它包括7行,其中6行对两个活动出席者具有YES事件,而1行对则具有NO事件。

因此,您应该只计算不同的值:

SELECT IF(uuid <=> NULL, 'NO', 'YES') as status, count(distinct(att.id)) as count 
   FROM attendants att 
   LEFT JOIN attendant_event ae ON ae.attendant_id = att.id 
   GROUP BY status

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM