jpa+mysql,union组合查询求和结果出错

UNION ALL

有两个表,A和B。

A表数据类似

id a1 a2 a3 a4 a5
1 5 0.5 a g1 ...
2 10 1.0 a g2 ...
3 15 1.5 a g1 ...

B表数据类似

id a1 a2 a3 a4 a5
1 10 2 b g2 ...
2 20 4 b g1 ...
3 30 6 b g1 ...


SELECT count(*), sum(x),sum(y),z,w FROM ( 
(SELECT a1 as x, a2 as y, a3 as z, a4 as w FROM A)
UNION ALL 
(SELECT b1 as x, b3 as z, b2 as y, b4 as w FROM B)
)t  GROUP BY w
结果发现,sum(x)结果是对的,但sum(y)是错的,为什么呢?

因为按照我的思路,UNION的select结果应该是:

x y z w
5 0.5 a g1
10 1.0 a g2
15 1.5 a g1
10 2 b g2
20 4 b g1
30 6 b g1

但实际上结果却是:

x y z w
5 0.5 a g1
10 1.0 a g2
15 1.5 a g1
10 b 2 g2
20 b 4 g1
30 b 6 g1

注意:y下面的三行不是数字,而是字母。

这时来看上面被union的两个select的字段顺序,

第一个是:a1,a2,a3,a4,

第二个是:b1,b3,b2,b4,

虽然其对应的xyzw都没对应错,但是:

union查询时并不会按你为各字段起的别名进行一一对应,而是按你的select时的字段顺序进行对应的

 


你可能感兴趣的:(jpa+mysql,union组合查询求和结果出错)