我对此查询有疑问:
Select id count(*)
....
....
....
....
UNION
Select id count(*)
.....
.....
.....
.....
输出是:
04123158-> 32
04123158-> 17
04123412-> 36
04132010-> 1473
我需要输出如下:
04123158-> 49
04123412-> 36
04132010-> 1473
在 UNION 中使用两个相似的 id 时会出现此问题。我想要一个唯一的总和结果。
我该怎么做?
最佳答案
您可以使用union
(实际上是union all
),然后聚合:
select id, sum(cnt)
from ((select id, count(*) as cnt . . .
) union all
(select is, count(*) as cnt . . .
)
) i
group by id
注意:您想要union all
有两个原因。首先,union
删除重复项。因此,如果两个 id
的 count(*)
值相同,则 union
将删除其中一行。 Union all
不会删除重复项。
其次,union
删除重复项。这会在查询中产生不必要的开销。为什么要增加额外的性能开销?
关于mysql - 使用 UNION 处理重复结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33692385/