使用 GROUP UNION 和 SUM 汇总单个 SQL 表上的多个向量
我正在尝试创建一个查询,该查询按关系类型返回表中所有实体的计数。例如。
1|VenueName1|0|0|0|
其中 0,0,0 是找到的关系数的计数。
该表本身包含许多不同外部项目类型的外部关系。每个关联可以以“向前”或“向后”的方式出现在表中,因此,例如,每个关系可以以两种方式之一出现:
|objectTypeId|objectId|associatedId |associatedTypeId|
| 13 | 1 | 8 | 2 |
| 2 | 8 | 1 | 13 |
有意义吗?它们通常只会出现一次,但可能出现在任一“方向”。因此,为了获得给定类型的总关系,我使用类似于以下的 UNION:
SELECT ip.id, ip.name, SUM(totalUnion.EventTotals) as Events
FROM iplace ip
LEFT JOIN
(
SELECT object_id, count(*) as EventTotals FROM `iassociation` ia
WHERE object_type_id=2 AND associated_object_type_id=14
GROUP BY object_id
UNION ALL
SELECT associated_object_id, count(*) as EventTotals FROM `iassociation` ia
WHERE associated_object_type_id=2 AND object_type_id=14
GROUP BY associated_object_id
) totalUnion ON ip.id = totalUnion.object_id
WHERE ip.type_id IN (4,7,11,15,16)
GROUP BY ip.id
工作正常。我的问题是我想对另外 2 个 typeId 执行相同的操作,再给出两个 SUM() 来显示不同的针对一个实体的关系类型总计。如果我添加额外的 LEFT JOIN,则会出现行重复并且计数被夸大。
希望这是有道理的。有人能提出解决方案吗?
I'm trying to create a query that returns counts by relationship type for all entities in a table. eg.
1|VenueName1|0|0|0|
where 0,0,0 is the counts for the number of relationships found.
The table itself contains a number of external relationships to many different external item types. Each association can appear in a 'forward' or 'backward' manner in the table, so for example, each relationship can appear one of two ways:
|objectTypeId|objectId|associatedId |associatedTypeId|
| 13 | 1 | 8 | 2 |
| 2 | 8 | 1 | 13 |
Makes sense? They will normally only appear once, but could be in either 'direction'. As such, to get the total relationships for a given type, I use a UNION similar to:
SELECT ip.id, ip.name, SUM(totalUnion.EventTotals) as Events
FROM iplace ip
LEFT JOIN
(
SELECT object_id, count(*) as EventTotals FROM `iassociation` ia
WHERE object_type_id=2 AND associated_object_type_id=14
GROUP BY object_id
UNION ALL
SELECT associated_object_id, count(*) as EventTotals FROM `iassociation` ia
WHERE associated_object_type_id=2 AND object_type_id=14
GROUP BY associated_object_id
) totalUnion ON ip.id = totalUnion.object_id
WHERE ip.type_id IN (4,7,11,15,16)
GROUP BY ip.id
That works ok.. My problem is that I want to do the same for another 2 typeIds, giving two more SUM()s to show different relationship type totals against the one entity. If I add eextra LEFT JOINs I get duplication of the rows and the counts are overstated.
Hope that makes some sense. Can anyone suggest a solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于您的子查询,您可以执行以下操作:
For your subquery you can do something like this: